platformMemory.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platformMemory.h"
  23. #include "console/dynamicTypes.h"
  24. #include "console/engineAPI.h"
  25. #include "core/stream/fileStream.h"
  26. #include "core/strings/stringFunctions.h"
  27. #include "console/console.h"
  28. #include "platform/profiler.h"
  29. #include "platform/threads/mutex.h"
  30. #include "core/module.h"
  31. // If profile paths are enabled, disable profiling of the
  32. // memory manager as that would cause a cyclic dependency
  33. // through the string table's allocation stuff used by the
  34. // profiler (talk about a long sentence...)
  35. #ifdef TORQUE_ENABLE_PROFILE_PATH
  36. # undef PROFILE_START
  37. # undef PROFILE_END
  38. # undef PROFILE_SCOPE
  39. # define PROFILE_START( x )
  40. # define PROFILE_END()
  41. # define PROFILE_SCOPE( x )
  42. #endif
  43. #ifdef TORQUE_MULTITHREAD
  44. void * gMemMutex = NULL;
  45. #endif
  46. //-------------------------------------- Make sure we don't have the define set
  47. #ifdef new
  48. #undef new
  49. #endif
  50. enum MemConstants {
  51. Allocated = BIT(0),
  52. Array = BIT(1),
  53. DebugFlag = BIT(2),
  54. Reallocated = BIT(3), /// This flag is set if the memory has been allocated, then 'realloc' is called
  55. GlobalFlag = BIT(4),
  56. StaticFlag = BIT(5),
  57. AllocatedGuard = 0xCEDEFEDE,
  58. FreeGuard = 0x5555FFFF,
  59. MaxAllocationAmount = 0xFFFFFFFF,
  60. TreeNodeAllocCount = 2048,
  61. };
  62. inline U32 flagToBit( Memory::EFlag flag )
  63. {
  64. using namespace Memory;
  65. U32 bit = 0;
  66. switch( flag )
  67. {
  68. case FLAG_Debug: bit = DebugFlag; break;
  69. case FLAG_Global: bit = GlobalFlag; break;
  70. case FLAG_Static: bit = StaticFlag; break;
  71. }
  72. return bit;
  73. }
  74. enum RedBlackTokens {
  75. Red = 0,
  76. Black = 1
  77. };
  78. static U32 MinPageSize = 8 * 1024 * 1024;
  79. #if !defined(TORQUE_SHIPPING) && defined(TORQUE_DEBUG_GUARD)
  80. #define LOG_PAGE_ALLOCS
  81. #endif
  82. U32 gNewNewTotal = 0;
  83. U32 gImageAlloc = 0;
  84. //---------------------------------------------------------------------------
  85. namespace Memory
  86. {
  87. ConsoleFunctionGroupBegin( Memory, "Memory manager utility functions.");
  88. struct FreeHeader;
  89. /// Red/Black Tree Node - used to store queues of free blocks
  90. struct TreeNode
  91. {
  92. U32 size;
  93. TreeNode *parent;
  94. TreeNode *left;
  95. TreeNode *right;
  96. U32 color;
  97. FreeHeader *queueHead;
  98. FreeHeader *queueTail;
  99. U32 unused;
  100. };
  101. struct Header
  102. {
  103. // doubly linked list of allocated and free blocks -
  104. // contiguous in memory.
  105. #ifdef TORQUE_DEBUG_GUARD
  106. U32 preguard[4];
  107. #endif
  108. Header *next;
  109. Header *prev;
  110. dsize_t size;
  111. U32 flags;
  112. #ifdef TORQUE_DEBUG_GUARD
  113. #ifdef TORQUE_ENABLE_PROFILE_PATH
  114. U32 unused[5];
  115. #else
  116. U32 unused[4];
  117. #endif
  118. U32 postguard[4];
  119. #endif
  120. };
  121. struct AllocatedHeader
  122. {
  123. #ifdef TORQUE_DEBUG_GUARD
  124. U32 preguard[4];
  125. #endif
  126. Header *next;
  127. Header *prev;
  128. dsize_t size;
  129. U32 flags;
  130. #ifdef TORQUE_DEBUG_GUARD
  131. // an allocated header will only have this stuff if TORQUE_DEBUG_GUARD
  132. U32 line;
  133. U32 allocNum;
  134. const char *fileName;
  135. #ifdef TORQUE_ENABLE_PROFILE_PATH
  136. const char * profilePath;
  137. #endif
  138. U32 realSize;
  139. U32 postguard[4];
  140. #endif
  141. void* getUserPtr()
  142. {
  143. return ( this + 1 );
  144. }
  145. };
  146. struct FreeHeader
  147. {
  148. #ifdef TORQUE_DEBUG_GUARD
  149. U32 preguard[4];
  150. #endif
  151. Header *next;
  152. Header *prev;
  153. dsize_t size;
  154. U32 flags;
  155. // since a free header has at least one cache line (16 bytes)
  156. // we can tag some more stuff on:
  157. FreeHeader *nextQueue; // of the same size
  158. FreeHeader *prevQueue; // doubly linked
  159. TreeNode *treeNode; // which tree node we're coming off of.
  160. U32 guard;
  161. #ifdef TORQUE_DEBUG_GUARD
  162. #ifdef TORQUE_ENABLE_PROFILE_PATH
  163. U32 unused;
  164. #endif
  165. U32 postguard[4];
  166. #endif
  167. };
  168. struct PageRecord
  169. {
  170. dsize_t allocSize;
  171. PageRecord *prevPage;
  172. Header *headerList; // if headerList is NULL, this is a treeNode page
  173. void *basePtr;
  174. U32 unused[4]; // even out the record to 32 bytes...
  175. // so if we're on a 32-byte cache-line comp, the tree nodes
  176. // will cache better
  177. };
  178. PageRecord *gPageList = NULL;
  179. TreeNode nil;
  180. TreeNode *NIL = &nil;
  181. TreeNode *gFreeTreeRoot = &nil;
  182. TreeNode *gTreeFreeList = NULL;
  183. U32 gInsertCount = 0;
  184. U32 gRemoveCount = 0;
  185. U32 gBreakAlloc = 0xFFFFFFFF;
  186. U32 gCurrAlloc = 0;
  187. char gLogFilename[256] = "memlog.txt";
  188. bool gEnableLogging = false;
  189. bool gNeverLogLeaks = 0;
  190. bool gAlwaysLogLeaks = 0;
  191. U32 gBytesAllocated = 0;
  192. U32 gBlocksAllocated = 0;
  193. U32 gPageBytesAllocated = 0;
  194. struct HeapIterator
  195. {
  196. PageRecord* mCurrentPage;
  197. Header* mCurrentHeader;
  198. bool mAllocatedOnly;
  199. HeapIterator( bool allocatedOnly = true )
  200. : mCurrentPage( gPageList ),
  201. mAllocatedOnly( allocatedOnly ),
  202. mCurrentHeader( NULL )
  203. {
  204. if( mCurrentPage )
  205. {
  206. mCurrentHeader = mCurrentPage->headerList;
  207. while( !mCurrentHeader && mCurrentPage )
  208. {
  209. mCurrentPage = mCurrentPage->prevPage;
  210. mCurrentHeader = mCurrentPage->headerList;
  211. }
  212. if( mCurrentHeader && mAllocatedOnly && !( mCurrentHeader->flags & Allocated ) )
  213. ++ ( *this ); // Advance to first allocated record.
  214. }
  215. }
  216. bool isValid() const
  217. {
  218. return ( mCurrentHeader != NULL );
  219. }
  220. HeapIterator& operator ++()
  221. {
  222. do
  223. {
  224. if( !mCurrentHeader )
  225. {
  226. if( mCurrentPage )
  227. mCurrentPage = mCurrentPage->prevPage;
  228. if( !mCurrentPage )
  229. break;
  230. mCurrentHeader = mCurrentPage->headerList;
  231. }
  232. else
  233. mCurrentHeader = mCurrentHeader->next;
  234. }
  235. while( !mCurrentHeader || ( mAllocatedOnly && !( mCurrentHeader->flags & Allocated ) ) );
  236. return *this;
  237. }
  238. operator Header*() const
  239. {
  240. return mCurrentHeader;
  241. }
  242. Header* operator *() const
  243. {
  244. return mCurrentHeader;
  245. }
  246. Header* operator ->() const
  247. {
  248. return mCurrentHeader;
  249. }
  250. };
  251. #ifdef TORQUE_DEBUG_GUARD
  252. static bool checkGuard(Header *header, bool alloc)
  253. {
  254. U32 guardVal = alloc ? AllocatedGuard : FreeGuard;
  255. for(U32 i = 0; i < 4; i++)
  256. if(header->preguard[i] != guardVal || header->postguard[i] != guardVal)
  257. {
  258. Platform::debugBreak();
  259. return false;
  260. }
  261. return true;
  262. }
  263. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  264. static void setGuard(Header *header, bool alloc)
  265. {
  266. U32 guardVal = alloc ? AllocatedGuard : FreeGuard;
  267. for(U32 i = 0; i < 4; i++)
  268. header->preguard[i] = header->postguard[i] = guardVal;
  269. }
  270. #endif // !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  271. #endif // TORQUE_DEBUG_GUARD
  272. static void memoryError()
  273. {
  274. // free all the pages
  275. PageRecord *walk = gPageList;
  276. while(walk) {
  277. PageRecord *prev = walk->prevPage;
  278. dRealFree(walk);
  279. walk = prev;
  280. }
  281. AssertFatal(false, "Error allocating memory! Shutting down.");
  282. Platform::AlertOK("Torque Memory Error", "Error allocating memory. Shutting down.\n");
  283. Platform::forceShutdown(-1);
  284. }
  285. PageRecord *allocPage(dsize_t pageSize)
  286. {
  287. pageSize += sizeof(PageRecord);
  288. void* base = dRealMalloc(pageSize);
  289. if (base == NULL)
  290. memoryError();
  291. PageRecord *rec = (PageRecord *) base;
  292. rec->basePtr = (void *) (rec + 1);
  293. rec->allocSize = pageSize;
  294. rec->prevPage = gPageList;
  295. gPageList = rec;
  296. rec->headerList = NULL;
  297. return rec;
  298. }
  299. TreeNode *allocTreeNode()
  300. {
  301. if(!gTreeFreeList)
  302. {
  303. PageRecord *newPage = allocPage(TreeNodeAllocCount * sizeof(TreeNode));
  304. TreeNode *walk = (TreeNode *) newPage->basePtr;
  305. U32 i;
  306. gTreeFreeList = walk;
  307. for(i = 0; i < TreeNodeAllocCount - 1; i++, walk++)
  308. walk->parent = walk + 1;
  309. walk->parent = NULL;
  310. }
  311. TreeNode *ret = gTreeFreeList;
  312. gTreeFreeList = ret->parent;
  313. return ret;
  314. }
  315. void freeTreeNode(TreeNode *tn)
  316. {
  317. tn->parent = gTreeFreeList;
  318. gTreeFreeList = tn;
  319. }
  320. static U32 validateTreeRecurse(TreeNode *tree)
  321. {
  322. if(tree == NIL)
  323. return 1;
  324. // check my left tree
  325. int lcount, rcount, nc = 0;
  326. if(tree->color == Red)
  327. {
  328. if(tree->left->color == Red || tree->right->color == Red)
  329. Platform::debugBreak();
  330. }
  331. else
  332. nc = 1;
  333. FreeHeader *walk = tree->queueHead;
  334. if(!walk)
  335. Platform::debugBreak();
  336. FreeHeader *prev = NULL;
  337. while(walk)
  338. {
  339. if(walk->prevQueue != prev)
  340. Platform::debugBreak();
  341. if(walk->treeNode != tree)
  342. Platform::debugBreak();
  343. if(walk->size != tree->size)
  344. Platform::debugBreak();
  345. if(!walk->nextQueue && walk != tree->queueTail)
  346. Platform::debugBreak();
  347. prev = walk;
  348. walk = walk->nextQueue;
  349. }
  350. lcount = validateTreeRecurse(tree->left);
  351. rcount = validateTreeRecurse(tree->right);
  352. if(lcount != rcount)
  353. Platform::debugBreak();
  354. return lcount + nc;
  355. }
  356. static void validateParentageRecurse(TreeNode *tree)
  357. {
  358. if(tree->left != NIL)
  359. {
  360. if(tree->left->parent != tree)
  361. Platform::debugBreak();
  362. if(tree->left->size > tree->size)
  363. Platform::debugBreak();
  364. validateParentageRecurse(tree->left);
  365. }
  366. if(tree->right != NIL)
  367. {
  368. if(tree->right->parent != tree)
  369. Platform::debugBreak();
  370. if(tree->right->size < tree->size)
  371. Platform::debugBreak();
  372. validateParentageRecurse(tree->right);
  373. }
  374. }
  375. static void validateTree()
  376. {
  377. if(gFreeTreeRoot == NIL)
  378. return;
  379. validateParentageRecurse(gFreeTreeRoot);
  380. validateTreeRecurse(gFreeTreeRoot);
  381. }
  382. void validate()
  383. {
  384. #ifdef TORQUE_MULTITHREAD
  385. if(!gMemMutex)
  386. gMemMutex = Mutex::createMutex();
  387. Mutex::lockMutex(gMemMutex);
  388. #endif
  389. // first validate the free tree:
  390. validateTree();
  391. // now validate all blocks:
  392. for(PageRecord *list = gPageList; list; list = list->prevPage)
  393. {
  394. Header *prev = NULL;
  395. for(Header *walk = list->headerList; walk; walk = walk->next)
  396. {
  397. #ifdef TORQUE_DEBUG_GUARD
  398. checkGuard(walk, walk->flags & Allocated);
  399. #endif
  400. if(walk->prev != prev)
  401. Platform::debugBreak();
  402. prev = walk;
  403. if(walk->next && ((const char *)(walk->next) != (const char *)(walk) + sizeof(Header) + walk->size))
  404. Platform::debugBreak();
  405. }
  406. }
  407. #ifdef TORQUE_MULTITHREAD
  408. Mutex::unlockMutex(gMemMutex);
  409. #endif
  410. }
  411. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  412. static void rotateLeft(TreeNode *hdr)
  413. {
  414. TreeNode *temp = hdr->right;
  415. hdr->right = temp->left;
  416. if(temp->left != NIL)
  417. temp->left->parent = hdr;
  418. temp->parent = hdr->parent;
  419. if(temp->parent == NIL)
  420. gFreeTreeRoot = temp;
  421. else if(hdr == hdr->parent->left)
  422. hdr->parent->left = temp;
  423. else
  424. hdr->parent->right = temp;
  425. temp->left = hdr;
  426. hdr->parent = temp;
  427. }
  428. #endif
  429. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  430. static void rotateRight(TreeNode *hdr)
  431. {
  432. TreeNode *temp = hdr->left;
  433. hdr->left = temp->right;
  434. if(temp->right != NIL)
  435. temp->right->parent = hdr;
  436. temp->parent = hdr->parent;
  437. if(temp->parent == NIL)
  438. gFreeTreeRoot = temp;
  439. else if(hdr == hdr->parent->left)
  440. hdr->parent->left = temp;
  441. else
  442. hdr->parent->right = temp;
  443. temp->right = hdr;
  444. hdr->parent = temp;
  445. }
  446. #endif
  447. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  448. static void treeInsert(FreeHeader *fhdr)
  449. {
  450. #ifdef TORQUE_DEBUG_GUARD
  451. checkGuard((Header *) fhdr, true); // check to see that it's got allocated guards
  452. setGuard((Header *) fhdr, false);
  453. #endif
  454. //gInsertCount++;
  455. TreeNode *newParent = NIL;
  456. TreeNode *walk = gFreeTreeRoot;
  457. while(walk != NIL)
  458. {
  459. newParent = walk;
  460. if(fhdr->size < walk->size)
  461. walk = walk->left;
  462. else if(fhdr->size > walk->size)
  463. walk = walk->right;
  464. else // tag it on the end of the queue...
  465. {
  466. // insert it on this header...
  467. walk->queueTail->nextQueue = fhdr;
  468. fhdr->prevQueue = walk->queueTail;
  469. walk->queueTail = fhdr;
  470. fhdr->nextQueue = NULL;
  471. fhdr->treeNode = walk;
  472. return;
  473. }
  474. }
  475. TreeNode *hdr = allocTreeNode();
  476. hdr->size = fhdr->size;
  477. hdr->queueHead = hdr->queueTail = fhdr;
  478. fhdr->nextQueue = fhdr->prevQueue = NULL;
  479. fhdr->treeNode = hdr;
  480. hdr->left = NIL;
  481. hdr->right = NIL;
  482. hdr->parent = newParent;
  483. if(newParent == NIL)
  484. gFreeTreeRoot = hdr;
  485. else if(hdr->size < newParent->size)
  486. newParent->left = hdr;
  487. else
  488. newParent->right = hdr;
  489. // do red/black rotations
  490. hdr->color = Red;
  491. while(hdr != gFreeTreeRoot && (hdr->parent->color == Red))
  492. {
  493. TreeNode *parent = hdr->parent;
  494. TreeNode *pparent = hdr->parent->parent;
  495. if(parent == pparent->left)
  496. {
  497. TreeNode *temp = pparent->right;
  498. if(temp->color == Red)
  499. {
  500. parent->color = Black;
  501. temp->color = Black;
  502. pparent->color = Red;
  503. hdr = pparent;
  504. }
  505. else
  506. {
  507. if(hdr == parent->right)
  508. {
  509. hdr = parent;
  510. rotateLeft(hdr);
  511. parent = hdr->parent;
  512. pparent = hdr->parent->parent;
  513. }
  514. parent->color = Black;
  515. pparent->color = Red;
  516. rotateRight(pparent);
  517. }
  518. }
  519. else
  520. {
  521. TreeNode *temp = pparent->left;
  522. if(temp->color == Red)
  523. {
  524. parent->color = Black;
  525. temp->color = Black;
  526. pparent->color = Red;
  527. hdr = pparent;
  528. }
  529. else
  530. {
  531. if(hdr == parent->left)
  532. {
  533. hdr = parent;
  534. rotateRight(hdr);
  535. parent = hdr->parent;
  536. pparent = hdr->parent->parent;
  537. }
  538. parent->color = Black;
  539. pparent->color = Red;
  540. rotateLeft(pparent);
  541. }
  542. }
  543. }
  544. gFreeTreeRoot->color = Black;
  545. //validateTree();
  546. }
  547. #endif
  548. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  549. static void treeRemove(FreeHeader *hdr)
  550. {
  551. #ifdef TORQUE_DEBUG_GUARD
  552. checkGuard((Header *) hdr, false);
  553. setGuard((Header *) hdr, true);
  554. #endif
  555. //validateTree();
  556. //gRemoveCount++;
  557. FreeHeader *prev = hdr->prevQueue;
  558. FreeHeader *next = hdr->nextQueue;
  559. if(prev)
  560. prev->nextQueue = next;
  561. else
  562. hdr->treeNode->queueHead = next;
  563. if(next)
  564. next->prevQueue = prev;
  565. else
  566. hdr->treeNode->queueTail = prev;
  567. if(prev || next)
  568. return;
  569. TreeNode *z = hdr->treeNode;
  570. nil.color = Black;
  571. TreeNode *y, *x;
  572. if(z->left == NIL || z->right == NIL)
  573. y = z;
  574. else
  575. {
  576. y = z->right;
  577. while(y->left != NIL)
  578. y = y->left;
  579. }
  580. if(y->left != NIL)
  581. x = y->left;
  582. else
  583. x = y->right;
  584. x->parent = y->parent;
  585. if(y->parent == NIL)
  586. gFreeTreeRoot = x;
  587. else if(y == y->parent->left)
  588. y->parent->left = x;
  589. else
  590. y->parent->right = x;
  591. U32 yColor = y->color;
  592. if(y != z)
  593. {
  594. // copy y's important fields into z (since we're going to free y)
  595. if(z->parent->left == z)
  596. z->parent->left = y;
  597. else if(z->parent->right == z)
  598. z->parent->right = y;
  599. y->left = z->left;
  600. y->right = z->right;
  601. if(y->left != NIL)
  602. y->left->parent = y;
  603. if(y->right != NIL)
  604. y->right->parent = y;
  605. y->parent = z->parent;
  606. if(z->parent == NIL)
  607. gFreeTreeRoot = y;
  608. y->color = z->color;
  609. if(x->parent == z)
  610. x->parent = y;
  611. //validateTree();
  612. }
  613. freeTreeNode(z);
  614. if(yColor == Black)
  615. {
  616. while(x != gFreeTreeRoot && x->color == Black)
  617. {
  618. TreeNode *w;
  619. if(x == x->parent->left)
  620. {
  621. w = x->parent->right;
  622. if(w->color == Red)
  623. {
  624. w->color = Black;
  625. x->parent->color = Red;
  626. rotateLeft(x->parent);
  627. w = x->parent->right;
  628. }
  629. if(w->left->color == Black && w->right->color == Black)
  630. {
  631. w->color = Red;
  632. x = x->parent;
  633. }
  634. else
  635. {
  636. if(w->right->color == Black)
  637. {
  638. w->left->color = Black;
  639. rotateRight(w);
  640. w = x->parent->right;
  641. }
  642. w->color = x->parent->color;
  643. x->parent->color = Black;
  644. w->right->color = Black;
  645. rotateLeft(x->parent);
  646. x = gFreeTreeRoot;
  647. }
  648. }
  649. else
  650. {
  651. w = x->parent->left;
  652. if(w->color == Red)
  653. {
  654. w->color = Black;
  655. x->parent->color = Red;
  656. rotateRight(x->parent);
  657. w = x->parent->left;
  658. }
  659. if(w->left->color == Black && w->right->color == Black)
  660. {
  661. w->color = Red;
  662. x = x->parent;
  663. }
  664. else
  665. {
  666. if(w->left->color == Black)
  667. {
  668. w->right->color = Black;
  669. rotateLeft(w);
  670. w = x->parent->left;
  671. }
  672. w->color = x->parent->color;
  673. x->parent->color = Black;
  674. w->left->color = Black;
  675. rotateRight(x->parent);
  676. x = gFreeTreeRoot;
  677. }
  678. }
  679. }
  680. x->color = Black;
  681. }
  682. //validateTree();
  683. }
  684. #endif
  685. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  686. static FreeHeader *treeFindSmallestGreaterThan(dsize_t size)
  687. {
  688. TreeNode *bestMatch = NIL;
  689. TreeNode *walk = gFreeTreeRoot;
  690. while(walk != NIL)
  691. {
  692. if(size == walk->size)
  693. return walk->queueHead;
  694. else if(size > walk->size)
  695. walk = walk->right;
  696. else // size < walk->size
  697. {
  698. bestMatch = walk;
  699. walk = walk->left;
  700. }
  701. }
  702. //validateTree();
  703. if(bestMatch != NIL)
  704. return bestMatch->queueHead;
  705. return NULL;
  706. }
  707. #endif
  708. /// Trigger a breakpoint if ptr is not a valid heap pointer or if its memory guards
  709. /// have been destroyed (only if TORQUE_DEBUG_GUARD is enabled).
  710. ///
  711. /// @note This function does not allow interior pointers!
  712. void checkPtr( void* ptr )
  713. {
  714. for( HeapIterator iter; iter.isValid(); ++ iter )
  715. {
  716. AllocatedHeader* header = ( AllocatedHeader* ) *iter;
  717. if( header->getUserPtr() == ptr )
  718. {
  719. char buffer[ 1024 ];
  720. #ifdef TORQUE_DEBUG_GUARD
  721. if( !checkGuard( *iter, true ) )
  722. {
  723. dSprintf( buffer, sizeof( buffer ), "0x%x is a valid heap pointer but has its guards corrupted", ptr );
  724. Platform::outputDebugString( buffer );
  725. return;
  726. }
  727. #endif
  728. //dSprintf( buffer, sizeof( buffer ), "0x%x is a valid heap pointer", ptr );
  729. //Platform::outputDebugString( buffer );
  730. return;
  731. }
  732. }
  733. char buffer[ 1024 ];
  734. dSprintf( buffer, sizeof( buffer ), "0x%x is not a valid heap pointer", ptr );
  735. Platform::outputDebugString( buffer );
  736. Platform::debugBreak();
  737. }
  738. /// Dump info on all memory blocks that are still allocated.
  739. /// @note Only works if TORQUE_DISABLE_MEMORY_MANAGER is not defined; otherwise this is a NOP.
  740. void ensureAllFreed()
  741. {
  742. #ifndef TORQUE_DISABLE_MEMORY_MANAGER
  743. U32 numLeaks = 0;
  744. U32 bytesLeaked = 0;
  745. for( HeapIterator iter; iter.isValid(); ++ iter )
  746. {
  747. AllocatedHeader* header = ( AllocatedHeader* ) *iter;
  748. if( !( header->flags & GlobalFlag ) )
  749. {
  750. // Note: can't spill profile paths here since they by
  751. // now are all invalid (they're on the now freed string table)
  752. #ifdef TORQUE_DEBUG_GUARD
  753. Platform::outputDebugString( "MEMORY LEAKED: 0x%x %i %s %s:%i = %i (%i)",
  754. header->getUserPtr(),
  755. header->allocNum,
  756. ( header->flags & StaticFlag ? "(static)" : "" ),
  757. header->fileName, header->line, header->realSize, header->size );
  758. numLeaks ++;
  759. bytesLeaked += header->size;
  760. #endif
  761. }
  762. }
  763. if( numLeaks )
  764. Platform::outputDebugString( "NUM LEAKS: %i (%i bytes)", numLeaks, bytesLeaked );
  765. #endif
  766. }
  767. struct MemDumpLog
  768. {
  769. U32 size;
  770. U32 count;
  771. U32 depthTotal;
  772. U32 maxDepth;
  773. U32 minDepth;
  774. };
  775. void logDumpTraverse(MemDumpLog *sizes, TreeNode *header, U32 depth)
  776. {
  777. if(header == NIL)
  778. return;
  779. MemDumpLog *mySize = sizes;
  780. while(mySize->size < header->size)
  781. mySize++;
  782. U32 cnt = 0;
  783. for(FreeHeader *walk = header->queueHead; walk; walk = walk->nextQueue)
  784. cnt++;
  785. mySize->count += cnt;
  786. mySize->depthTotal += depth * cnt;
  787. mySize->maxDepth = depth > mySize->maxDepth ? depth : mySize->maxDepth;
  788. mySize->minDepth = depth < mySize->minDepth ? depth : mySize->minDepth;
  789. logDumpTraverse(sizes, header->left, depth + 1);
  790. logDumpTraverse(sizes, header->right, depth + 1);
  791. }
  792. #ifdef TORQUE_DEBUG
  793. DefineConsoleFunction( validateMemory, void, ( ),,
  794. "@brief Used to validate memory space for the game.\n\n"
  795. "@ingroup Debugging" )
  796. {
  797. validate();
  798. }
  799. #endif
  800. DefineConsoleFunction( freeMemoryDump, void, ( ),,
  801. "@brief Dumps some useful statistics regarding free memory.\n\n"
  802. "Dumps an analysis of \'free chunks\' of memory. "
  803. "Does not print how much memory is free.\n\n"
  804. "@ingroup Debugging" )
  805. {
  806. U32 startSize = 16;
  807. MemDumpLog memSizes[20];
  808. U32 i;
  809. for(i = 0; i < 20; i++)
  810. {
  811. memSizes[i].size = startSize << i;
  812. memSizes[i].count = 0;
  813. memSizes[i].depthTotal = 0;
  814. memSizes[i].maxDepth = 0;
  815. memSizes[i].minDepth = 1000;
  816. }
  817. memSizes[19].size = MaxAllocationAmount;
  818. logDumpTraverse(memSizes, gFreeTreeRoot, 1);
  819. MemDumpLog fullMem;
  820. fullMem.count = 0;
  821. fullMem.depthTotal = 0;
  822. fullMem.maxDepth = 0;
  823. fullMem.minDepth = 1000;
  824. for(i = 0; i < 20; i++)
  825. {
  826. if(memSizes[i].count)
  827. Con::printf("Size: %d - Free blocks: %d Max Depth: %d Min Depth: %d Average Depth: %g",
  828. memSizes[i].size, memSizes[i].count, memSizes[i].maxDepth, memSizes[i].minDepth,
  829. F32(memSizes[i].depthTotal) / F32(memSizes[i].count));
  830. fullMem.count += memSizes[i].count;
  831. fullMem.depthTotal += memSizes[i].depthTotal;
  832. fullMem.maxDepth = memSizes[i].maxDepth > fullMem.maxDepth ? memSizes[i].maxDepth : fullMem.maxDepth;
  833. fullMem.minDepth = memSizes[i].minDepth < fullMem.minDepth ? memSizes[i].minDepth : fullMem.minDepth;
  834. }
  835. Con::printf("Total free blocks: %d Max Depth: %d Min Depth: %d Average Depth: %g",
  836. fullMem.count, fullMem.maxDepth, fullMem.minDepth, F32(fullMem.depthTotal) / F32(fullMem.count));
  837. }
  838. #ifdef TORQUE_DEBUG_GUARD
  839. void flagCurrentAllocs( EFlag flag )
  840. {
  841. #ifdef TORQUE_ENABLE_PROFILE_PATH
  842. if (gProfiler && !gProfiler->isEnabled())
  843. {
  844. gProfiler->enable(true);
  845. // warm it up
  846. //gProfiler->dumpToConsole();
  847. }
  848. #endif
  849. U32 bit = flagToBit( flag );
  850. for( HeapIterator iter; iter.isValid(); ++ iter )
  851. iter->flags |= bit;
  852. }
  853. DefineEngineFunction(flagCurrentAllocs, void, (),,
  854. "@brief Flags all current memory allocations.\n\n"
  855. "Flags all current memory allocations for exclusion in subsequent calls to dumpUnflaggedAllocs(). "
  856. "Helpful in detecting memory leaks and analyzing memory usage.\n\n"
  857. "@ingroup Debugging" )
  858. {
  859. flagCurrentAllocs();
  860. }
  861. void dumpUnflaggedAllocs(const char *file, EFlag flag)
  862. {
  863. countUnflaggedAllocs(file, NULL, flag);
  864. }
  865. S32 countUnflaggedAllocs(const char * filename, S32 *outUnflaggedRealloc, EFlag flag)
  866. {
  867. S32 unflaggedAllocCount = 0;
  868. S32 unflaggedReAllocCount = 0;
  869. FileStream fws;
  870. bool useFile = filename && *filename;
  871. if (useFile)
  872. useFile = fws.open(filename, Torque::FS::File::Write);
  873. char buffer[1024];
  874. U32 bit = flagToBit( flag );
  875. PageRecord* walk;
  876. for (walk = gPageList; walk; walk = walk->prevPage)
  877. {
  878. for(Header *probe = walk->headerList; probe; probe = probe->next)
  879. {
  880. if (probe->flags & Allocated)
  881. {
  882. AllocatedHeader* pah = (AllocatedHeader*)probe;
  883. if (!(pah->flags & bit))
  884. {
  885. // If you want to extract further information from an unflagged
  886. // memory allocation, do the following:
  887. // U8 *foo = (U8 *)pah;
  888. // foo += sizeof(Header);
  889. // FooObject *obj = (FooObject *)foo;
  890. dSprintf(buffer, 1023, "%s%s\t%d\t%d\t%d\r\n",
  891. pah->flags & Reallocated ? "[R] " : "",
  892. pah->fileName != NULL ? pah->fileName : "Undetermined",
  893. pah->line, pah->realSize, pah->allocNum);
  894. if( pah->flags & Reallocated )
  895. unflaggedReAllocCount++;
  896. else
  897. unflaggedAllocCount++;
  898. if (useFile)
  899. {
  900. fws.write(dStrlen(buffer), buffer);
  901. fws.write(2, "\r\n");
  902. }
  903. else
  904. {
  905. if( pah->flags & Reallocated )
  906. Con::warnf(buffer);
  907. else
  908. Con::errorf(buffer);
  909. }
  910. #ifdef TORQUE_ENABLE_PROFILE_PATH
  911. static char line[4096];
  912. dSprintf(line, sizeof(line), " %s\r\nreal size=%d",
  913. pah->profilePath ? pah->profilePath : "unknown",
  914. pah->realSize);
  915. if (useFile)
  916. {
  917. fws.write(dStrlen(line), line);
  918. fws.write(2, "\r\n");
  919. }
  920. else
  921. {
  922. if( pah->flags & Reallocated )
  923. Con::warnf(line);
  924. else
  925. Con::errorf(line);
  926. }
  927. #endif
  928. }
  929. }
  930. }
  931. }
  932. if (useFile)
  933. fws.close();
  934. if( outUnflaggedRealloc != NULL )
  935. *outUnflaggedRealloc = unflaggedReAllocCount;
  936. return unflaggedAllocCount;
  937. }
  938. DefineEngineFunction(dumpUnflaggedAllocs, void, ( const char* fileName ), ( "" ),
  939. "@brief Dumps all unflagged memory allocations.\n\n"
  940. "Dumps all memory allocations that were made after a call to flagCurrentAllocs(). "
  941. "Helpful when used with flagCurrentAllocs() for detecting memory leaks and analyzing general memory usage.\n\n"
  942. "@param fileName Optional file path and location to dump all memory allocations not flagged by flagCurrentAllocs(). "
  943. "If left blank, data will be dumped to the console.\n\n"
  944. "@tsexample\n"
  945. "dumpMemSnapshot(); // dumps info to console\n"
  946. "dumpMemSnapshot( \"C:/Torque/profilerlog1.txt\" ); // dumps info to file\n"
  947. "@endtsexample\n\n"
  948. "@note Available in debug builds only. "
  949. "In torqueConfig.h, TORQUE_DISABLE_MEMORY_MANAGER must be undefined to use this function.\n\n"
  950. "@ingroup Debugging" )
  951. {
  952. dumpUnflaggedAllocs(fileName);
  953. }
  954. static void initLog()
  955. {
  956. static const char* sInitString = " --- INIT MEMORY LOG (ACTION): (FILE) (LINE) (SIZE) (ALLOCNUMBER) ---\r\n";
  957. FileStream fws;
  958. fws.open(gLogFilename, Torque::FS::File::Write);
  959. fws.write(dStrlen(sInitString), sInitString);
  960. fws.close();
  961. }
  962. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  963. static void logAlloc(const AllocatedHeader* hdr, S32 memSize)
  964. {
  965. FileStream fws;
  966. fws.open(gLogFilename, Torque::FS::File::ReadWrite);
  967. fws.setPosition(fws.getStreamSize());
  968. char buffer[1024];
  969. dSprintf(buffer, 1023, "alloc: %s %d %d %d\r\n",
  970. hdr->fileName != NULL ? hdr->fileName : "Undetermined",
  971. hdr->line, memSize, hdr->allocNum);
  972. fws.write(dStrlen(buffer), buffer);
  973. fws.close();
  974. }
  975. #endif
  976. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  977. static void logRealloc(const AllocatedHeader* hdr, S32 memSize)
  978. {
  979. FileStream fws;
  980. fws.open(gLogFilename, Torque::FS::File::ReadWrite);
  981. fws.setPosition(fws.getStreamSize());
  982. char buffer[1024];
  983. dSprintf(buffer, 1023, "realloc: %s %d %d %d\r\n",
  984. hdr->fileName != NULL ? hdr->fileName : "Undetermined",
  985. hdr->line, memSize, hdr->allocNum);
  986. fws.write(dStrlen(buffer), buffer);
  987. fws.close();
  988. }
  989. #endif
  990. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  991. static void logFree(const AllocatedHeader* hdr)
  992. {
  993. FileStream fws;
  994. fws.open(gLogFilename, Torque::FS::File::ReadWrite);
  995. fws.setPosition(fws.getStreamSize());
  996. char buffer[1024];
  997. dSprintf(buffer, 1023, "free: %s %d %d\r\n",
  998. hdr->fileName != NULL ? hdr->fileName : "Undetermined",
  999. hdr->line, hdr->allocNum);
  1000. fws.write(dStrlen(buffer), buffer);
  1001. fws.close();
  1002. }
  1003. #endif // !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  1004. #endif
  1005. void enableLogging(const char* fileName)
  1006. {
  1007. dStrcpy(gLogFilename, fileName);
  1008. if (!gEnableLogging)
  1009. {
  1010. gEnableLogging = true;
  1011. #ifdef TORQUE_DEBUG_GUARD
  1012. initLog();
  1013. #endif
  1014. }
  1015. }
  1016. void disableLogging()
  1017. {
  1018. gLogFilename[0] = '\0';
  1019. gEnableLogging = false;
  1020. }
  1021. // CodeReview - this is never called so commented out to save warning.
  1022. // Do we want to re-enable it? Might be nice to get leak tracking on
  1023. // exit...or maybe that is just a problematical feature we shouldn't
  1024. // worry about.
  1025. //static void shutdown()
  1026. //{
  1027. //#ifdef TORQUE_MULTITHREAD
  1028. // Mutex::destroyMutex(gMemMutex);
  1029. // gMemMutex = NULL;
  1030. //#endif
  1031. //
  1032. //#ifdef TORQUE_DEBUG_GUARD
  1033. //
  1034. // // write out leaks and such
  1035. // const U32 maxNumLeaks = 1024;
  1036. // U32 numLeaks = 0;
  1037. //
  1038. // AllocatedHeader* pLeaks[maxNumLeaks];
  1039. // for (PageRecord * walk = gPageList; walk; walk = walk->prevPage)
  1040. // for(Header *probe = walk->headerList; probe; probe = probe->next)
  1041. // if ((probe->flags & Allocated) && ((AllocatedHeader *)probe)->fileName != NULL)
  1042. // pLeaks[numLeaks++] = (AllocatedHeader *) probe;
  1043. //
  1044. // if (numLeaks && !gNeverLogLeaks)
  1045. // {
  1046. // if (gAlwaysLogLeaks || Platform::AlertOKCancel("Memory Status", "Memory leaks detected. Write to memoryLeaks.log?") == true)
  1047. // {
  1048. // char buffer[1024];
  1049. // FileStream logFile;
  1050. // logFile.open("memoryLeaks.log", Torque::FS::File::Write);
  1051. //
  1052. // for (U32 i = 0; i < numLeaks; i++)
  1053. // {
  1054. // dSprintf(buffer, 1023, "Leak in %s: %d (%d)\r\n", pLeaks[i]->fileName, pLeaks[i]->line, pLeaks[i]->allocNum);
  1055. // logFile.write(dStrlen(buffer), buffer);
  1056. // }
  1057. // logFile.close();
  1058. // }
  1059. // }
  1060. //#endif
  1061. //
  1062. // // then free all the memory pages
  1063. // for (PageRecord * walk = gPageList; walk; )
  1064. // {
  1065. // PageRecord *prev = walk->prevPage;
  1066. // dRealFree(walk);
  1067. // walk = prev;
  1068. // }
  1069. //}
  1070. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  1071. static Header *allocMemPage(dsize_t pageSize)
  1072. {
  1073. pageSize += sizeof(Header);
  1074. if(pageSize < MinPageSize)
  1075. pageSize = MinPageSize;
  1076. PageRecord *base = allocPage(pageSize);
  1077. Header* rec = (Header*)base->basePtr;
  1078. base->headerList = rec;
  1079. rec->size = pageSize - sizeof(Header);
  1080. rec->next = NULL;
  1081. rec->prev = NULL;
  1082. rec->flags = 0;
  1083. #ifdef TORQUE_DEBUG_GUARD
  1084. setGuard(rec, true);
  1085. #endif
  1086. #ifdef LOG_PAGE_ALLOCS
  1087. gPageBytesAllocated += pageSize;
  1088. // total bytes allocated so far will be 0 when TORQUE_DEBUG_GUARD is disabled, so convert that into more meaningful string
  1089. const U32 StrSize = 256;
  1090. char strBytesAllocated[StrSize];
  1091. if (gBytesAllocated > 0)
  1092. dSprintf(strBytesAllocated, sizeof(strBytesAllocated), "%i", gBytesAllocated);
  1093. else
  1094. dStrncpy(strBytesAllocated,"unknown - enable TORQUE_DEBUG_GUARD", StrSize);
  1095. #ifndef TORQUE_MULTITHREAD // May deadlock.
  1096. // NOTE: This code may be called within Con::_printf, and if that is the case
  1097. // this will infinitly recurse. This is the reason for the code in Con::_printf
  1098. // that sets Con::active to false. -patw
  1099. if (Con::isActive())
  1100. Con::errorf("PlatformMemory: allocating new page, total bytes allocated so far: %s (total bytes in all pages=%i)",strBytesAllocated,gPageBytesAllocated);
  1101. #endif
  1102. #endif
  1103. return rec;
  1104. }
  1105. #endif
  1106. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  1107. static void checkUnusedAlloc(FreeHeader *header, U32 size)
  1108. {
  1109. //validate();
  1110. if(header->size >= size + sizeof(Header) + 16)
  1111. {
  1112. U8 *basePtr = (U8 *) header;
  1113. basePtr += sizeof(Header);
  1114. FreeHeader *newHeader = (FreeHeader *) (basePtr + size);
  1115. newHeader->next = header->next;
  1116. newHeader->prev = (Header *) header;
  1117. header->next = (Header *) newHeader;
  1118. if(newHeader->next)
  1119. newHeader->next->prev = (Header *) newHeader;
  1120. newHeader->flags = 0;
  1121. newHeader->size = header->size - size - sizeof(Header);
  1122. header->size = size;
  1123. #ifdef TORQUE_DEBUG_GUARD
  1124. setGuard((Header *) newHeader, true);
  1125. #endif
  1126. treeInsert(newHeader);
  1127. }
  1128. }
  1129. #endif
  1130. #if defined(TORQUE_MULTITHREAD) && !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  1131. static bool gReentrantGuard = false;
  1132. #endif
  1133. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  1134. static void* alloc(dsize_t size, bool array, const char* fileName, const U32 line)
  1135. {
  1136. AssertFatal(size < MaxAllocationAmount, "Memory::alloc - tried to allocate > MaxAllocationAmount!");
  1137. #ifdef TORQUE_MULTITHREAD
  1138. if(!gMemMutex && !gReentrantGuard)
  1139. {
  1140. gReentrantGuard = true;
  1141. gMemMutex = Mutex::createMutex();
  1142. gReentrantGuard = false;
  1143. }
  1144. if(!gReentrantGuard)
  1145. Mutex::lockMutex(gMemMutex);
  1146. #endif
  1147. AssertFatal(size < MaxAllocationAmount, "Size error.");
  1148. //validate();
  1149. if (size == 0)
  1150. {
  1151. #ifdef TORQUE_MULTITHREAD
  1152. if(!gReentrantGuard)
  1153. Mutex::unlockMutex(gMemMutex);
  1154. #endif
  1155. return NULL;
  1156. }
  1157. #ifndef TORQUE_ENABLE_PROFILE_PATH
  1158. // Note: will cause crash if profile path is on
  1159. PROFILE_START(MemoryAlloc);
  1160. #endif
  1161. #ifdef TORQUE_DEBUG_GUARD
  1162. // if we're guarding, round up to the nearest DWORD
  1163. size = ((size + 3) & ~0x3);
  1164. #else
  1165. // round up size to nearest 16 byte boundary (cache lines and all...)
  1166. size = ((size + 15) & ~0xF);
  1167. #endif
  1168. FreeHeader *header = treeFindSmallestGreaterThan(size);
  1169. if(header)
  1170. treeRemove(header);
  1171. else
  1172. header = (FreeHeader *) allocMemPage(size);
  1173. // ok, see if there's enough room in the block to make another block
  1174. // for this to happen it has to have enough room for a header
  1175. // and 16 more bytes.
  1176. U8 *basePtr = (U8 *) header;
  1177. basePtr += sizeof(Header);
  1178. checkUnusedAlloc(header, size);
  1179. AllocatedHeader *retHeader = (AllocatedHeader *) header;
  1180. retHeader->flags = array ? (Allocated | Array) : Allocated;
  1181. #ifdef TORQUE_DEBUG_GUARD
  1182. retHeader->line = line;
  1183. retHeader->fileName = fileName;
  1184. retHeader->allocNum = gCurrAlloc;
  1185. retHeader->realSize = size;
  1186. #ifdef TORQUE_ENABLE_PROFILE_PATH
  1187. retHeader->profilePath = gProfiler ? gProfiler->getProfilePath() : "pre";
  1188. #endif
  1189. gBytesAllocated += size;
  1190. gBlocksAllocated ++;
  1191. //static U32 skip = 0;
  1192. //if ((++skip % 1000) == 0)
  1193. // Con::printf("new=%i, newnew=%i, imagenew=%i",gBytesAllocated,gNewNewTotal,gImageAlloc);
  1194. if (gEnableLogging)
  1195. logAlloc(retHeader, size);
  1196. #endif
  1197. if(gCurrAlloc == gBreakAlloc && gBreakAlloc != 0xFFFFFFFF)
  1198. Platform::debugBreak();
  1199. gCurrAlloc++;
  1200. #ifndef TORQUE_ENABLE_PROFILE_PATH
  1201. PROFILE_END();
  1202. #endif
  1203. //validate();
  1204. #ifdef TORQUE_DEBUG
  1205. // fill the block with the fill value. although this is done in free(), that won't fill
  1206. // newly allocated MM memory (which hasn't been freed yet). We use a different fill value
  1207. // to diffentiate filled freed memory from filled new memory; this may aid debugging.
  1208. #ifndef TORQUE_ENABLE_PROFILE_PATH
  1209. PROFILE_START(stompMem1);
  1210. #endif
  1211. dMemset(basePtr, 0xCF, size);
  1212. #ifndef TORQUE_ENABLE_PROFILE_PATH
  1213. PROFILE_END();
  1214. #endif
  1215. #endif
  1216. if(gCurrAlloc == gBreakAlloc && gBreakAlloc != 0xFFFFFFFF)
  1217. Platform::debugBreak();
  1218. gCurrAlloc++;
  1219. #ifdef TORQUE_MULTITHREAD
  1220. if(!gReentrantGuard)
  1221. Mutex::unlockMutex(gMemMutex);
  1222. #endif
  1223. return basePtr;
  1224. }
  1225. #endif
  1226. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  1227. static void free(void* mem, bool array)
  1228. {
  1229. // validate();
  1230. if (!mem)
  1231. return;
  1232. #ifdef TORQUE_MULTITHREAD
  1233. if(!gMemMutex)
  1234. gMemMutex = Mutex::createMutex();
  1235. if( mem != gMemMutex )
  1236. Mutex::lockMutex(gMemMutex);
  1237. else
  1238. gMemMutex = NULL;
  1239. #endif
  1240. PROFILE_START(MemoryFree);
  1241. AllocatedHeader *hdr = ((AllocatedHeader *)mem) - 1;
  1242. AssertFatal(hdr->flags & Allocated, avar("Not an allocated block!"));
  1243. AssertFatal(((bool)((hdr->flags & Array)==Array))==array, avar("Array alloc mismatch. "));
  1244. gBlocksAllocated --;
  1245. #ifdef TORQUE_DEBUG_GUARD
  1246. gBytesAllocated -= hdr->realSize;
  1247. if (gEnableLogging)
  1248. logFree(hdr);
  1249. #endif
  1250. hdr->flags = 0;
  1251. // fill the block with the fill value
  1252. #ifdef TORQUE_DEBUG
  1253. #ifndef TORQUE_ENABLE_PROFILE_PATH
  1254. PROFILE_START(stompMem2);
  1255. #endif
  1256. dMemset(mem, 0xCE, hdr->size);
  1257. #ifndef TORQUE_ENABLE_PROFILE_PATH
  1258. PROFILE_END();
  1259. #endif
  1260. #endif
  1261. // see if we can merge hdr with the block after it.
  1262. Header* next = hdr->next;
  1263. if (next && next->flags == 0)
  1264. {
  1265. treeRemove((FreeHeader *) next);
  1266. hdr->size += next->size + sizeof(Header);
  1267. hdr->next = next->next;
  1268. if(next->next)
  1269. next->next->prev = (Header *) hdr;
  1270. }
  1271. // see if we can merge hdr with the block before it.
  1272. Header* prev = hdr->prev;
  1273. if (prev && prev->flags == 0)
  1274. {
  1275. treeRemove((FreeHeader *) prev);
  1276. prev->size += hdr->size + sizeof(Header);
  1277. prev->next = hdr->next;
  1278. if (hdr->next)
  1279. hdr->next->prev = prev;
  1280. hdr = (AllocatedHeader *) prev;
  1281. }
  1282. // throw this puppy into the tree!
  1283. treeInsert((FreeHeader *) hdr);
  1284. PROFILE_END();
  1285. // validate();
  1286. #ifdef TORQUE_MULTITHREAD
  1287. Mutex::unlockMutex(gMemMutex);
  1288. #endif
  1289. }
  1290. #endif
  1291. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  1292. static void* realloc(void* mem, dsize_t size, const char* fileName, const U32 line)
  1293. {
  1294. //validate();
  1295. if (!size) {
  1296. free(mem, false);
  1297. return NULL;
  1298. }
  1299. if(!mem)
  1300. return alloc(size, false, fileName, line);
  1301. #ifdef TORQUE_MULTITHREAD
  1302. if(!gMemMutex)
  1303. gMemMutex = Mutex::createMutex();
  1304. Mutex::lockMutex(gMemMutex);
  1305. #endif
  1306. AllocatedHeader* hdr = ((AllocatedHeader *)mem) - 1;
  1307. #ifdef TORQUE_DEBUG_GUARD
  1308. checkGuard( ( Header* ) hdr, true );
  1309. #endif
  1310. AssertFatal((hdr->flags & Allocated) == Allocated, "Bad block flags.");
  1311. size = (size + 0xF) & ~0xF;
  1312. U32 oldSize = hdr->size;
  1313. if(oldSize == size)
  1314. {
  1315. #ifdef TORQUE_MULTITHREAD
  1316. Mutex::unlockMutex(gMemMutex);
  1317. #endif
  1318. return mem;
  1319. }
  1320. PROFILE_START(MemoryRealloc);
  1321. FreeHeader *next = (FreeHeader *) hdr->next;
  1322. #ifdef TORQUE_DEBUG_GUARD
  1323. // adjust header size and allocated bytes size
  1324. hdr->realSize += size - oldSize;
  1325. gBytesAllocated += size - oldSize;
  1326. if (gEnableLogging)
  1327. logRealloc(hdr, size);
  1328. // Add reallocated flag, note header changes will not persist if the realloc
  1329. // decides tofree, and then perform a fresh allocation for the memory. The flag will
  1330. // be manually set again after this takes place, down at the bottom of this fxn.
  1331. hdr->flags |= Reallocated;
  1332. // Note on Above ^
  1333. // A more useful/robust implementation can be accomplished by storing an additional
  1334. // AllocatedHeader* in DEBUG_GUARD builds inside the AllocatedHeader structure
  1335. // itself to create a sort of reallocation history. This will be, essentially,
  1336. // a allocation header stack for each allocation. Each time the memory is reallocated
  1337. // it should use dRealMalloc (IMPORTANT!!) to allocate a AllocatedHeader* and chain
  1338. // it to the reallocation history chain, and the dump output changed to display
  1339. // reallocation history. It is also important to clean up this chain during 'free'
  1340. // using dRealFree (Since memory for the chain was allocated via dRealMalloc).
  1341. //
  1342. // See patw for details.
  1343. #endif
  1344. if (next && !(next->flags & Allocated) && next->size + hdr->size + sizeof(Header) >= size)
  1345. {
  1346. // we can merge with the next dude.
  1347. treeRemove(next);
  1348. hdr->size += sizeof(Header) + next->size;
  1349. hdr->next = next->next;
  1350. if(next->next)
  1351. next->next->prev = (Header *) hdr;
  1352. checkUnusedAlloc((FreeHeader *) hdr, size);
  1353. //validate();
  1354. PROFILE_END();
  1355. #ifdef TORQUE_MULTITHREAD
  1356. Mutex::unlockMutex(gMemMutex);
  1357. #endif
  1358. return mem;
  1359. }
  1360. else if(size < oldSize)
  1361. {
  1362. checkUnusedAlloc((FreeHeader *) hdr, size);
  1363. PROFILE_END();
  1364. #ifdef TORQUE_MULTITHREAD
  1365. Mutex::unlockMutex(gMemMutex);
  1366. #endif
  1367. return mem;
  1368. }
  1369. #ifdef TORQUE_DEBUG_GUARD
  1370. // undo above adjustment because we're going though alloc instead
  1371. hdr->realSize -= size - oldSize;
  1372. gBytesAllocated -= size - oldSize;
  1373. #endif
  1374. void* ret = alloc(size, false, fileName, line);
  1375. dMemcpy(ret, mem, oldSize);
  1376. free(mem, false);
  1377. PROFILE_END();
  1378. // Re-enable the 'Reallocated' flag so that this allocation can be ignored by
  1379. // a non-strict run of the flag/dumpunflagged.
  1380. hdr = ((AllocatedHeader *)ret) - 1;
  1381. hdr->flags |= Reallocated;
  1382. #ifdef TORQUE_MULTITHREAD
  1383. Mutex::unlockMutex(gMemMutex);
  1384. #endif
  1385. return ret;
  1386. }
  1387. #endif
  1388. dsize_t getMemoryUsed()
  1389. {
  1390. U32 size = 0;
  1391. PageRecord* walk;
  1392. for (walk = gPageList; walk; walk = walk->prevPage) {
  1393. for(Header *probe = walk->headerList; probe; probe = probe->next)
  1394. if (probe->flags & Allocated) {
  1395. size += probe->size;
  1396. }
  1397. }
  1398. return size;
  1399. }
  1400. #ifdef TORQUE_DEBUG_GUARD
  1401. DefineEngineFunction( dumpAlloc, void, ( int allocNum ),,
  1402. "@brief Dumps information about the given allocated memory block.\n\n"
  1403. "@param allocNum Memory block to dump information about."
  1404. "@note Available in debug builds only. "
  1405. "In torqueConfig.h, TORQUE_DISABLE_MEMORY_MANAGER must be undefined to use this function.\n\n"
  1406. "@ingroup Debugging")
  1407. {
  1408. PageRecord* walk;
  1409. for( walk = gPageList; walk; walk = walk->prevPage )
  1410. for( Header* probe = walk->headerList; probe; probe = probe->next )
  1411. if( probe->flags & Allocated )
  1412. {
  1413. AllocatedHeader* pah = ( AllocatedHeader* ) probe;
  1414. if( pah->allocNum == allocNum )
  1415. {
  1416. Con::printf( "file: %s\n"
  1417. "line: %i\n"
  1418. "size: %i\n"
  1419. "allocNum: %i\n"
  1420. "reallocated: %s",
  1421. pah->fileName != NULL ? pah->fileName : "Undetermined",
  1422. pah->line,
  1423. pah->realSize,
  1424. pah->allocNum,
  1425. pah->flags & Reallocated ? "yes" : "no"
  1426. );
  1427. // Dump the profile path, if we have one.
  1428. #ifdef TORQUE_ENABLE_PROFILE_PATH
  1429. if( pah->profilePath && pah->profilePath[ 0 ] )
  1430. Con::printf( "profilepath: %s", pah->profilePath );
  1431. #endif
  1432. }
  1433. }
  1434. }
  1435. DefineEngineFunction( dumpMemSnapshot, void, ( const char* fileName ),,
  1436. "@brief Dumps a snapshot of current memory to a file.\n\n"
  1437. "The total memory used will also be output to the console.\n"
  1438. "This function will attempt to create the file if it does not already exist.\n"
  1439. "@param fileName Name and path of file to save profiling stats to. Must use forward slashes (/)\n"
  1440. "@tsexample\n"
  1441. "dumpMemSnapshot( \"C:/Torque/ProfilerLogs/profilerlog1.txt\" );\n"
  1442. "@endtsexample\n\n"
  1443. "@note Available in debug builds only. "
  1444. "In torqueConfig.h, TORQUE_DISABLE_MEMORY_MANAGER must be undefined to use this function.\n\n"
  1445. "@ingroup Debugging")
  1446. {
  1447. FileStream fws;
  1448. fws.open(fileName, Torque::FS::File::Write);
  1449. char buffer[ 2048 ];
  1450. PageRecord* walk;
  1451. for (walk = gPageList; walk; walk = walk->prevPage) {
  1452. for(Header *probe = walk->headerList; probe; probe = probe->next)
  1453. if (probe->flags & Allocated) {
  1454. AllocatedHeader* pah = (AllocatedHeader*)probe;
  1455. dSprintf( buffer, sizeof( buffer ), "%s%s\t%d\t%d\t%d\r\n",
  1456. pah->flags & Reallocated ? "[R] " : "",
  1457. pah->fileName != NULL ? pah->fileName : "Undetermined",
  1458. pah->line, pah->realSize, pah->allocNum);
  1459. fws.write(dStrlen(buffer), buffer);
  1460. // Dump the profile path, if we have one.
  1461. #ifdef TORQUE_ENABLE_PROFILE_PATH
  1462. if( pah->profilePath )
  1463. {
  1464. dSprintf( buffer, sizeof( buffer ), "%s\r\n\r\n", pah->profilePath );
  1465. fws.write( dStrlen( buffer ), buffer );
  1466. }
  1467. #endif
  1468. }
  1469. }
  1470. Con::errorf("total memory used: %d",getMemoryUsed());
  1471. fws.close();
  1472. }
  1473. #endif
  1474. dsize_t getMemoryAllocated()
  1475. {
  1476. return 0;
  1477. }
  1478. void getMemoryInfo( void* ptr, Info& info )
  1479. {
  1480. #ifndef TORQUE_DISABLE_MEMORY_MANAGER
  1481. AllocatedHeader* header = ( ( AllocatedHeader* ) ptr ) - 1;
  1482. info.mAllocSize = header->size;
  1483. #ifdef TORQUE_DEBUG_GUARD
  1484. info.mAllocNumber = header->allocNum;
  1485. info.mLineNumber = header->line;
  1486. info.mFileName = header->fileName;
  1487. #endif
  1488. info.mIsArray = header->flags & Array;
  1489. info.mIsGlobal = header->flags & GlobalFlag;
  1490. info.mIsStatic = header->flags & StaticFlag;
  1491. #endif
  1492. }
  1493. void setBreakAlloc(U32 breakAlloc)
  1494. {
  1495. gBreakAlloc = breakAlloc;
  1496. }
  1497. ConsoleFunctionGroupEnd( Memory );
  1498. } // namespace Memory
  1499. void setMinimumAllocUnit(U32 allocUnit)
  1500. {
  1501. AssertFatal(isPow2(allocUnit) && allocUnit > (2 << 20),
  1502. "Error, allocunit must be a power of two, and greater than 2 megs");
  1503. MinPageSize = allocUnit;
  1504. }
  1505. //---------------------------------------------------------------------------
  1506. //---------------------------------------------------------------------------
  1507. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  1508. // Manage our own memory, add overloaded memory operators and functions
  1509. void* FN_CDECL operator new(dsize_t size, const char* fileName, const U32 line)
  1510. {
  1511. return Memory::alloc(size, false, fileName, line);
  1512. }
  1513. void* FN_CDECL operator new[](dsize_t size, const char* fileName, const U32 line)
  1514. {
  1515. return Memory::alloc(size, true, fileName, line);
  1516. }
  1517. void* FN_CDECL operator new(dsize_t size)
  1518. {
  1519. return Memory::alloc(size, false, NULL, 0);
  1520. }
  1521. void* FN_CDECL operator new[](dsize_t size)
  1522. {
  1523. return Memory::alloc(size, true, NULL, 0);
  1524. }
  1525. void FN_CDECL operator delete(void* mem)
  1526. {
  1527. Memory::free(mem, false);
  1528. }
  1529. void FN_CDECL operator delete[](void* mem)
  1530. {
  1531. Memory::free(mem, true);
  1532. }
  1533. void* dMalloc_r(dsize_t in_size, const char* fileName, const dsize_t line)
  1534. {
  1535. return Memory::alloc(in_size, false, fileName, line);
  1536. }
  1537. void dFree(void* in_pFree)
  1538. {
  1539. Memory::free(in_pFree, false);
  1540. }
  1541. void* dRealloc_r(void* in_pResize, dsize_t in_size, const char* fileName, const dsize_t line)
  1542. {
  1543. return Memory::realloc(in_pResize, in_size, fileName, line);
  1544. }
  1545. AFTER_MODULE_INIT( Sim )
  1546. {
  1547. Con::addVariable( "$Memory::numBlocksAllocated", TypeS32, &Memory::gBlocksAllocated,
  1548. "Total number of memory blocks currently allocated.\n\n"
  1549. "@ingroup Debugging" );
  1550. Con::addVariable( "$Memory::numBytesAllocated", TypeS32, &Memory::gBytesAllocated,
  1551. "Total number of bytes currently allocated.\n\n"
  1552. "@ingroup Debugging" );
  1553. }
  1554. #else
  1555. // Don't manage our own memory
  1556. void* dMalloc_r(dsize_t in_size, const char* fileName, const dsize_t line)
  1557. {
  1558. return malloc(in_size);
  1559. }
  1560. void dFree(void* in_pFree)
  1561. {
  1562. free(in_pFree);
  1563. }
  1564. void* dRealloc_r(void* in_pResize, dsize_t in_size, const char* fileName, const dsize_t line)
  1565. {
  1566. return realloc(in_pResize,in_size);
  1567. }
  1568. #endif