platformMemory.cpp 48 KB

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