platformMemory.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793
  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. S32 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. #ifdef TORQUE_DEBUG_GUARD
  720. char buffer[ 1024 ];
  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. //dSprintf( buffer, sizeof( buffer ), "0x%x is a valid heap pointer", ptr );
  728. //Platform::outputDebugString( buffer );
  729. #endif
  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, ( S32 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