as_gc.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2013 Andreas Jonsson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you
  11. must not claim that you wrote the original software. If you use
  12. this software in a product, an acknowledgment in the product
  13. documentation would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. The original version of this library can be located at:
  19. http://www.angelcode.com/angelscript/
  20. Andreas Jonsson
  21. [email protected]
  22. */
  23. //
  24. // as_gc.cpp
  25. //
  26. // The implementation of the garbage collector
  27. //
  28. #include <stdlib.h>
  29. #include "as_gc.h"
  30. #include "as_scriptengine.h"
  31. #include "as_scriptobject.h"
  32. #include "as_texts.h"
  33. BEGIN_AS_NAMESPACE
  34. asCGarbageCollector::asCGarbageCollector()
  35. {
  36. engine = 0;
  37. detectState = clearCounters_init;
  38. destroyNewState = destroyGarbage_init;
  39. destroyOldState = destroyGarbage_init;
  40. numDestroyed = 0;
  41. numNewDestroyed = 0;
  42. numDetected = 0;
  43. isProcessing = false;
  44. }
  45. asCGarbageCollector::~asCGarbageCollector()
  46. {
  47. // This local typedef is done to workaround a compiler error on
  48. // MSVC6 when using the typedef declared in the class definition
  49. typedef asSMapNode_t node_t;
  50. for( asUINT n = 0; n < freeNodes.GetLength(); n++ )
  51. asDELETE(freeNodes[n], node_t);
  52. freeNodes.SetLength(0);
  53. }
  54. bool asCGarbageCollector::IsObjectInGC(void *obj)
  55. {
  56. asUINT n;
  57. for( n = 0; n < gcNewObjects.GetLength(); n++ )
  58. if( gcNewObjects[n].obj == obj )
  59. return true;
  60. for( n = 0; n < gcOldObjects.GetLength(); n++ )
  61. if( gcOldObjects[n].obj == obj )
  62. return true;
  63. return false;
  64. }
  65. void asCGarbageCollector::AddScriptObjectToGC(void *obj, asCObjectType *objType)
  66. {
  67. if( obj == 0 || objType == 0 )
  68. {
  69. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_GC_RECEIVED_NULL_PTR);
  70. return;
  71. }
  72. engine->CallObjectMethod(obj, objType->beh.addref);
  73. asSObjTypePair ot = {obj, objType, 0};
  74. // Invoke the garbage collector to destroy a little garbage as new comes in
  75. // This will maintain the number of objects in the GC at a maintainable level without
  76. // halting the application, and without burdening the application with manually invoking the
  77. // garbage collector.
  78. if( engine->ep.autoGarbageCollect && gcNewObjects.GetLength() )
  79. {
  80. // If the GC is already processing in another thread, then don't try this again
  81. if( TRYENTERCRITICALSECTION(gcCollecting) )
  82. {
  83. // Skip this if the GC is already running in this thread
  84. if( !isProcessing )
  85. {
  86. isProcessing = true;
  87. // TODO: The number of iterations should be dynamic, and increase
  88. // if the number of objects in the garbage collector grows high
  89. // Run one step of DetectGarbage
  90. if( gcOldObjects.GetLength() )
  91. {
  92. IdentifyGarbageWithCyclicRefs();
  93. DestroyOldGarbage();
  94. }
  95. // Run a few steps of DestroyGarbage
  96. int iter = (int)gcNewObjects.GetLength();
  97. if( iter > 10 ) iter = 10;
  98. while( iter-- > 0 )
  99. DestroyNewGarbage();
  100. isProcessing = false;
  101. }
  102. LEAVECRITICALSECTION(gcCollecting);
  103. }
  104. }
  105. // Add the data to the gcObjects array in a critical section as
  106. // another thread might be calling this method at the same time
  107. ENTERCRITICALSECTION(gcCritical);
  108. gcNewObjects.PushLast(ot);
  109. LEAVECRITICALSECTION(gcCritical);
  110. }
  111. int asCGarbageCollector::GarbageCollect(asDWORD flags)
  112. {
  113. // If the GC is already processing in another thread, then don't enter here again
  114. if( TRYENTERCRITICALSECTION(gcCollecting) )
  115. {
  116. // If the GC is already processing in this thread, then don't enter here again
  117. if( isProcessing )
  118. {
  119. LEAVECRITICALSECTION(gcCollecting);
  120. return 1;
  121. }
  122. isProcessing = true;
  123. bool doDetect = (flags & asGC_DETECT_GARBAGE) || !(flags & asGC_DESTROY_GARBAGE);
  124. bool doDestroy = (flags & asGC_DESTROY_GARBAGE) || !(flags & asGC_DETECT_GARBAGE);
  125. if( flags & asGC_FULL_CYCLE )
  126. {
  127. // Reset the state
  128. if( doDetect )
  129. {
  130. // Move all objects to the old list, so we guarantee that all is detected
  131. for( asUINT n = (asUINT)gcNewObjects.GetLength(); n-- > 0; )
  132. MoveObjectToOldList(n);
  133. detectState = clearCounters_init;
  134. }
  135. if( doDestroy )
  136. {
  137. destroyNewState = destroyGarbage_init;
  138. destroyOldState = destroyGarbage_init;
  139. }
  140. unsigned int count = (unsigned int)(gcNewObjects.GetLength() + gcOldObjects.GetLength());
  141. for(;;)
  142. {
  143. // Detect all garbage with cyclic references
  144. if( doDetect )
  145. while( IdentifyGarbageWithCyclicRefs() == 1 ) {}
  146. // Now destroy all known garbage
  147. if( doDestroy )
  148. {
  149. while( DestroyNewGarbage() == 1 ) {}
  150. while( DestroyOldGarbage() == 1 ) {}
  151. }
  152. // Run another iteration if any garbage was destroyed
  153. if( count != (unsigned int)(gcNewObjects.GetLength() + gcOldObjects.GetLength()) )
  154. count = (unsigned int)(gcNewObjects.GetLength() + gcOldObjects.GetLength());
  155. else
  156. {
  157. // Let the engine destroy the types that reached refCount 0
  158. // If none were destroyed, then leave the GC
  159. // TODO: The asCObjectType should destroy its content when refCount reaches 0
  160. // since no-one is using them. The registered types should have their
  161. // refcount increased by the config groups. Doing it like that will allow
  162. // me to remove this call to ClearUnusedTypes() that the GC really
  163. // shouldn't be calling.
  164. if( engine->ClearUnusedTypes() == 0 )
  165. break;
  166. }
  167. }
  168. isProcessing = false;
  169. LEAVECRITICALSECTION(gcCollecting);
  170. return 0;
  171. }
  172. else
  173. {
  174. // Destroy the garbage that we know of
  175. if( doDestroy )
  176. {
  177. DestroyNewGarbage();
  178. DestroyOldGarbage();
  179. }
  180. // Run another incremental step of the identification of cyclic references
  181. if( doDetect )
  182. IdentifyGarbageWithCyclicRefs();
  183. }
  184. isProcessing = false;
  185. LEAVECRITICALSECTION(gcCollecting);
  186. }
  187. // Return 1 to indicate that the cycle wasn't finished
  188. return 1;
  189. }
  190. void asCGarbageCollector::GetStatistics(asUINT *currentSize, asUINT *totalDestroyed, asUINT *totalDetected, asUINT *newObjects, asUINT *totalNewDestroyed) const
  191. {
  192. // It's not necessary to protect this access, as
  193. // it doesn't matter if another thread is currently
  194. // appending a new object.
  195. if( currentSize )
  196. *currentSize = (asUINT)(gcNewObjects.GetLength() + gcOldObjects.GetLength());
  197. if( totalDestroyed )
  198. *totalDestroyed = numDestroyed;
  199. if( totalDetected )
  200. *totalDetected = numDetected;
  201. if( newObjects )
  202. *newObjects = (asUINT)gcNewObjects.GetLength();
  203. if( totalNewDestroyed )
  204. *totalNewDestroyed = numNewDestroyed;
  205. }
  206. asCGarbageCollector::asSObjTypePair asCGarbageCollector::GetNewObjectAtIdx(int idx)
  207. {
  208. // We need to protect this access with a critical section as
  209. // another thread might be appending an object at the same time
  210. ENTERCRITICALSECTION(gcCritical);
  211. asSObjTypePair gcObj = gcNewObjects[idx];
  212. LEAVECRITICALSECTION(gcCritical);
  213. return gcObj;
  214. }
  215. asCGarbageCollector::asSObjTypePair asCGarbageCollector::GetOldObjectAtIdx(int idx)
  216. {
  217. // We need to protect this access with a critical section as
  218. // another thread might be appending an object at the same time
  219. ENTERCRITICALSECTION(gcCritical);
  220. asSObjTypePair gcObj = gcOldObjects[idx];
  221. LEAVECRITICALSECTION(gcCritical);
  222. return gcObj;
  223. }
  224. void asCGarbageCollector::RemoveNewObjectAtIdx(int idx)
  225. {
  226. // We need to protect this update with a critical section as
  227. // another thread might be appending an object at the same time
  228. ENTERCRITICALSECTION(gcCritical);
  229. if( idx == (int)gcNewObjects.GetLength() - 1)
  230. gcNewObjects.PopLast();
  231. else
  232. gcNewObjects[idx] = gcNewObjects.PopLast();
  233. LEAVECRITICALSECTION(gcCritical);
  234. }
  235. void asCGarbageCollector::RemoveOldObjectAtIdx(int idx)
  236. {
  237. // We need to protect this update with a critical section as
  238. // another thread might be appending an object at the same time
  239. ENTERCRITICALSECTION(gcCritical);
  240. if( idx == (int)gcOldObjects.GetLength() - 1)
  241. gcOldObjects.PopLast();
  242. else
  243. gcOldObjects[idx] = gcOldObjects.PopLast();
  244. LEAVECRITICALSECTION(gcCritical);
  245. }
  246. void asCGarbageCollector::MoveObjectToOldList(int idx)
  247. {
  248. // We need to protect this update with a critical section as
  249. // another thread might be appending an object at the same time
  250. ENTERCRITICALSECTION(gcCritical);
  251. gcOldObjects.PushLast(gcNewObjects[idx]);
  252. if( idx == (int)gcNewObjects.GetLength() - 1)
  253. gcNewObjects.PopLast();
  254. else
  255. gcNewObjects[idx] = gcNewObjects.PopLast();
  256. LEAVECRITICALSECTION(gcCritical);
  257. }
  258. void asCGarbageCollector::IncreaseCounterForNewObject(int idx)
  259. {
  260. // We need to protect this update with a critical section as
  261. // another thread might be appending an object at the same time
  262. ENTERCRITICALSECTION(gcCritical);
  263. gcNewObjects[idx].count++;
  264. LEAVECRITICALSECTION(gcCritical);
  265. }
  266. int asCGarbageCollector::DestroyNewGarbage()
  267. {
  268. for(;;)
  269. {
  270. switch( destroyNewState )
  271. {
  272. case destroyGarbage_init:
  273. {
  274. // If there are no objects to be freed then don't start
  275. if( gcNewObjects.GetLength() == 0 )
  276. return 0;
  277. destroyNewIdx = (asUINT)-1;
  278. destroyNewState = destroyGarbage_loop;
  279. }
  280. break;
  281. case destroyGarbage_loop:
  282. case destroyGarbage_haveMore:
  283. {
  284. // If the refCount has reached 1, then only the GC still holds a
  285. // reference to the object, thus we don't need to worry about the
  286. // application touching the objects during collection.
  287. // Destroy all objects that have refCount == 1. If any objects are
  288. // destroyed, go over the list again, because it may have made more
  289. // objects reach refCount == 1.
  290. if( ++destroyNewIdx < gcNewObjects.GetLength() )
  291. {
  292. asSObjTypePair gcObj = GetNewObjectAtIdx(destroyNewIdx);
  293. if( engine->CallObjectMethodRetInt(gcObj.obj, gcObj.type->beh.gcGetRefCount) == 1 )
  294. {
  295. // Release the object immediately
  296. // Make sure the refCount is really 0, because the
  297. // destructor may have increased the refCount again.
  298. bool addRef = false;
  299. if( gcObj.type->flags & asOBJ_SCRIPT_OBJECT )
  300. {
  301. // Script objects may actually be resurrected in the destructor
  302. int refCount = ((asCScriptObject*)gcObj.obj)->Release();
  303. if( refCount > 0 ) addRef = true;
  304. }
  305. else
  306. engine->CallObjectMethod(gcObj.obj, gcObj.type->beh.release);
  307. // Was the object really destroyed?
  308. if( !addRef )
  309. {
  310. numDestroyed++;
  311. numNewDestroyed++;
  312. RemoveNewObjectAtIdx(destroyNewIdx);
  313. destroyNewIdx--;
  314. }
  315. else
  316. {
  317. // Since the object was resurrected in the
  318. // destructor, we must add our reference again
  319. engine->CallObjectMethod(gcObj.obj, gcObj.type->beh.addref);
  320. }
  321. destroyNewState = destroyGarbage_haveMore;
  322. }
  323. else if( gcObj.count == 3 )
  324. {
  325. // We've already verified this object multiple times. It is likely
  326. // to live for quite a long time so we'll move it to the list if old objects
  327. MoveObjectToOldList(destroyNewIdx);
  328. destroyNewIdx--;
  329. }
  330. else
  331. {
  332. // Increase the counter for the number of times the object has been verified
  333. IncreaseCounterForNewObject(destroyNewIdx);
  334. }
  335. // Allow the application to work a little
  336. return 1;
  337. }
  338. else
  339. {
  340. if( destroyNewState == destroyGarbage_haveMore )
  341. {
  342. // Restart the cycle
  343. destroyNewState = destroyGarbage_init;
  344. }
  345. else
  346. {
  347. // Restart the cycle
  348. destroyNewState = destroyGarbage_init;
  349. // Return 0 to tell the application that there
  350. // is no more garbage to destroy at the moment
  351. return 0;
  352. }
  353. }
  354. }
  355. break;
  356. }
  357. }
  358. // Shouldn't reach this point
  359. UNREACHABLE_RETURN;
  360. }
  361. int asCGarbageCollector::ReportAndReleaseUndestroyedObjects()
  362. {
  363. int items = 0;
  364. for( asUINT n = 0; n < gcOldObjects.GetLength(); n++ )
  365. {
  366. asSObjTypePair gcObj = GetOldObjectAtIdx(n);
  367. // Report the object as not being properly destroyed
  368. asCString msg;
  369. msg.Format(TXT_GC_CANNOT_FREE_OBJ_OF_TYPE_s, gcObj.type->name.AddressOf());
  370. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, msg.AddressOf());
  371. // Release the reference that the GC holds if the release functions is still available
  372. if( gcObj.type->beh.release && engine->scriptFunctions[gcObj.type->beh.release] )
  373. engine->CallObjectMethod(gcObj.obj, gcObj.type->beh.release);
  374. items++;
  375. }
  376. return items;
  377. }
  378. int asCGarbageCollector::DestroyOldGarbage()
  379. {
  380. for(;;)
  381. {
  382. switch( destroyOldState )
  383. {
  384. case destroyGarbage_init:
  385. {
  386. // If there are no objects to be freed then don't start
  387. if( gcOldObjects.GetLength() == 0 )
  388. return 0;
  389. destroyOldIdx = (asUINT)-1;
  390. destroyOldState = destroyGarbage_loop;
  391. }
  392. break;
  393. case destroyGarbage_loop:
  394. case destroyGarbage_haveMore:
  395. {
  396. // If the refCount has reached 1, then only the GC still holds a
  397. // reference to the object, thus we don't need to worry about the
  398. // application touching the objects during collection.
  399. // Destroy all objects that have refCount == 1. If any objects are
  400. // destroyed, go over the list again, because it may have made more
  401. // objects reach refCount == 1.
  402. if( ++destroyOldIdx < gcOldObjects.GetLength() )
  403. {
  404. asSObjTypePair gcObj = GetOldObjectAtIdx(destroyOldIdx);
  405. if( gcObj.type->beh.gcGetRefCount == 0 )
  406. {
  407. // If circular references are formed with registered types that hasn't
  408. // registered the GC behaviours, then the engine may be forced to free
  409. // the object type before the actual object instance. In this case we
  410. // will be forced to skip the destruction of the objects, so as not to
  411. // crash the application.
  412. asCString msg;
  413. msg.Format(TXT_GC_CANNOT_FREE_OBJ_OF_TYPE_s, gcObj.type->name.AddressOf());
  414. engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, msg.AddressOf());
  415. // Just remove the object, as we will not bother to destroy it
  416. numDestroyed++;
  417. RemoveOldObjectAtIdx(destroyOldIdx);
  418. destroyOldIdx--;
  419. }
  420. else if( engine->CallObjectMethodRetInt(gcObj.obj, gcObj.type->beh.gcGetRefCount) == 1 )
  421. {
  422. // Release the object immediately
  423. // Make sure the refCount is really 0, because the
  424. // destructor may have increased the refCount again.
  425. bool addRef = false;
  426. if( gcObj.type->flags & asOBJ_SCRIPT_OBJECT )
  427. {
  428. // Script objects may actually be resurrected in the destructor
  429. int refCount = ((asCScriptObject*)gcObj.obj)->Release();
  430. if( refCount > 0 ) addRef = true;
  431. }
  432. else
  433. engine->CallObjectMethod(gcObj.obj, gcObj.type->beh.release);
  434. // Was the object really destroyed?
  435. if( !addRef )
  436. {
  437. numDestroyed++;
  438. RemoveOldObjectAtIdx(destroyOldIdx);
  439. destroyOldIdx--;
  440. }
  441. else
  442. {
  443. // Since the object was resurrected in the
  444. // destructor, we must add our reference again
  445. engine->CallObjectMethod(gcObj.obj, gcObj.type->beh.addref);
  446. }
  447. destroyOldState = destroyGarbage_haveMore;
  448. }
  449. // Allow the application to work a little
  450. return 1;
  451. }
  452. else
  453. {
  454. if( destroyOldState == destroyGarbage_haveMore )
  455. {
  456. // Restart the cycle
  457. destroyOldState = destroyGarbage_init;
  458. }
  459. else
  460. {
  461. // Restart the cycle
  462. destroyOldState = destroyGarbage_init;
  463. // Return 0 to tell the application that there
  464. // is no more garbage to destroy at the moment
  465. return 0;
  466. }
  467. }
  468. }
  469. break;
  470. }
  471. }
  472. // Shouldn't reach this point
  473. UNREACHABLE_RETURN;
  474. }
  475. int asCGarbageCollector::IdentifyGarbageWithCyclicRefs()
  476. {
  477. for(;;)
  478. {
  479. switch( detectState )
  480. {
  481. case clearCounters_init:
  482. detectState = clearCounters_loop;
  483. break;
  484. case clearCounters_loop:
  485. {
  486. // Decrease reference counter for all objects removed from the map
  487. asSMapNode<void*, asSIntTypePair> *cursor = 0;
  488. gcMap.MoveFirst(&cursor);
  489. if( cursor )
  490. {
  491. void *obj = gcMap.GetKey(cursor);
  492. asSIntTypePair it = gcMap.GetValue(cursor);
  493. engine->CallObjectMethod(obj, it.type->beh.release);
  494. ReturnNode(gcMap.Remove(cursor));
  495. return 1;
  496. }
  497. detectState = buildMap_init;
  498. }
  499. break;
  500. case buildMap_init:
  501. detectIdx = 0;
  502. detectState = buildMap_loop;
  503. break;
  504. case buildMap_loop:
  505. {
  506. // Build a map of objects that will be checked, the map will
  507. // hold the object pointer as key, and the gcCount and the
  508. // object's type as value. As objects are added to the map the
  509. // gcFlag must be set in the objects, so we can be verify if
  510. // the object is accessed during the GC cycle.
  511. // If an object is removed from the gcObjects list during the
  512. // iteration of this step, it is possible that an object won't
  513. // be used during the analyzing for cyclic references. This
  514. // isn't a problem, as the next time the GC cycle starts the
  515. // object will be verified.
  516. if( detectIdx < gcOldObjects.GetLength() )
  517. {
  518. // Add the gc count for this object
  519. asSObjTypePair gcObj = GetOldObjectAtIdx(detectIdx);
  520. int refCount = 0;
  521. if( gcObj.type->beh.gcGetRefCount )
  522. refCount = engine->CallObjectMethodRetInt(gcObj.obj, gcObj.type->beh.gcGetRefCount);
  523. if( refCount > 1 )
  524. {
  525. asSIntTypePair it = {refCount-1, gcObj.type};
  526. gcMap.Insert(GetNode(gcObj.obj, it));
  527. // Increment the object's reference counter when putting it in the map
  528. engine->CallObjectMethod(gcObj.obj, gcObj.type->beh.addref);
  529. // Mark the object so that we can
  530. // see if it has changed since read
  531. engine->CallObjectMethod(gcObj.obj, gcObj.type->beh.gcSetFlag);
  532. }
  533. detectIdx++;
  534. // Let the application work a little
  535. return 1;
  536. }
  537. else
  538. detectState = countReferences_init;
  539. }
  540. break;
  541. case countReferences_init:
  542. {
  543. gcMap.MoveFirst(&gcMapCursor);
  544. detectState = countReferences_loop;
  545. }
  546. break;
  547. case countReferences_loop:
  548. {
  549. // Call EnumReferences on all objects in the map to count the number
  550. // of references reachable from between objects in the map. If all
  551. // references for an object in the map is reachable from other objects
  552. // in the map, then we know that no outside references are held for
  553. // this object, thus it is a potential dead object in a circular reference.
  554. // If the gcFlag is cleared for an object we consider the object alive
  555. // and referenced from outside the GC, thus we don't enumerate its references.
  556. // Any new objects created after this step in the GC cycle won't be
  557. // in the map, and is thus automatically considered alive.
  558. if( gcMapCursor )
  559. {
  560. void *obj = gcMap.GetKey(gcMapCursor);
  561. asCObjectType *type = gcMap.GetValue(gcMapCursor).type;
  562. gcMap.MoveNext(&gcMapCursor, gcMapCursor);
  563. if( engine->CallObjectMethodRetBool(obj, type->beh.gcGetFlag) )
  564. {
  565. engine->CallObjectMethod(obj, engine, type->beh.gcEnumReferences);
  566. }
  567. // Allow the application to work a little
  568. return 1;
  569. }
  570. else
  571. detectState = detectGarbage_init;
  572. }
  573. break;
  574. case detectGarbage_init:
  575. {
  576. gcMap.MoveFirst(&gcMapCursor);
  577. liveObjects.SetLength(0);
  578. detectState = detectGarbage_loop1;
  579. }
  580. break;
  581. case detectGarbage_loop1:
  582. {
  583. // All objects that are known not to be dead must be removed from the map,
  584. // along with all objects they reference. What remains in the map after
  585. // this pass is sure to be dead objects in circular references.
  586. // An object is considered alive if its gcFlag is cleared, or all the
  587. // references were not found in the map.
  588. // Add all alive objects from the map to the liveObjects array
  589. if( gcMapCursor )
  590. {
  591. asSMapNode<void*, asSIntTypePair> *cursor = gcMapCursor;
  592. gcMap.MoveNext(&gcMapCursor, gcMapCursor);
  593. void *obj = gcMap.GetKey(cursor);
  594. asSIntTypePair it = gcMap.GetValue(cursor);
  595. bool gcFlag = engine->CallObjectMethodRetBool(obj, it.type->beh.gcGetFlag);
  596. if( !gcFlag || it.i > 0 )
  597. {
  598. liveObjects.PushLast(obj);
  599. }
  600. // Allow the application to work a little
  601. return 1;
  602. }
  603. else
  604. detectState = detectGarbage_loop2;
  605. }
  606. break;
  607. case detectGarbage_loop2:
  608. {
  609. // In this step we are actually removing the alive objects from the map.
  610. // As the object is removed, all the objects it references are added to the
  611. // liveObjects list, by calling EnumReferences. Only objects still in the map
  612. // will be added to the liveObjects list.
  613. if( liveObjects.GetLength() )
  614. {
  615. void *gcObj = liveObjects.PopLast();
  616. asCObjectType *type = 0;
  617. // Remove the object from the map to mark it as alive
  618. asSMapNode<void*, asSIntTypePair> *cursor = 0;
  619. if( gcMap.MoveTo(&cursor, gcObj) )
  620. {
  621. type = gcMap.GetValue(cursor).type;
  622. ReturnNode(gcMap.Remove(cursor));
  623. // We need to decrease the reference count again as we remove the object from the map
  624. engine->CallObjectMethod(gcObj, type->beh.release);
  625. // Enumerate all the object's references so that they too can be marked as alive
  626. engine->CallObjectMethod(gcObj, engine, type->beh.gcEnumReferences);
  627. }
  628. // Allow the application to work a little
  629. return 1;
  630. }
  631. else
  632. detectState = verifyUnmarked_init;
  633. }
  634. break;
  635. case verifyUnmarked_init:
  636. gcMap.MoveFirst(&gcMapCursor);
  637. detectState = verifyUnmarked_loop;
  638. break;
  639. case verifyUnmarked_loop:
  640. {
  641. // In this step we must make sure that none of the objects still in the map
  642. // has been touched by the application. If they have then we must run the
  643. // detectGarbage loop once more.
  644. if( gcMapCursor )
  645. {
  646. void *gcObj = gcMap.GetKey(gcMapCursor);
  647. asCObjectType *type = gcMap.GetValue(gcMapCursor).type;
  648. bool gcFlag = engine->CallObjectMethodRetBool(gcObj, type->beh.gcGetFlag);
  649. if( !gcFlag )
  650. {
  651. // The unmarked object was touched, rerun the detectGarbage loop
  652. detectState = detectGarbage_init;
  653. }
  654. else
  655. gcMap.MoveNext(&gcMapCursor, gcMapCursor);
  656. // Allow the application to work a little
  657. return 1;
  658. }
  659. else
  660. {
  661. // No unmarked object was touched, we can now be sure
  662. // that objects that have gcCount == 0 really is garbage
  663. detectState = breakCircles_init;
  664. }
  665. }
  666. break;
  667. case breakCircles_init:
  668. {
  669. gcMap.MoveFirst(&gcMapCursor);
  670. detectState = breakCircles_loop;
  671. }
  672. break;
  673. case breakCircles_loop:
  674. case breakCircles_haveGarbage:
  675. {
  676. // All objects in the map are now known to be dead objects
  677. // kept alive through circular references. To be able to free
  678. // these objects we need to force the breaking of the circle
  679. // by having the objects release their references.
  680. if( gcMapCursor )
  681. {
  682. numDetected++;
  683. void *gcObj = gcMap.GetKey(gcMapCursor);
  684. asCObjectType *type = gcMap.GetValue(gcMapCursor).type;
  685. engine->CallObjectMethod(gcObj, engine, type->beh.gcReleaseAllReferences);
  686. gcMap.MoveNext(&gcMapCursor, gcMapCursor);
  687. detectState = breakCircles_haveGarbage;
  688. // Allow the application to work a little
  689. return 1;
  690. }
  691. else
  692. {
  693. // If no garbage was detected we can finish now
  694. if( detectState != breakCircles_haveGarbage )
  695. {
  696. // Restart the GC
  697. detectState = clearCounters_init;
  698. return 0;
  699. }
  700. else
  701. {
  702. // Restart the GC
  703. detectState = clearCounters_init;
  704. return 1;
  705. }
  706. }
  707. }
  708. } // switch
  709. }
  710. // Shouldn't reach this point
  711. UNREACHABLE_RETURN;
  712. }
  713. asCGarbageCollector::asSMapNode_t *asCGarbageCollector::GetNode(void *obj, asSIntTypePair it)
  714. {
  715. asSMapNode_t *node;
  716. if( freeNodes.GetLength() )
  717. node = freeNodes.PopLast();
  718. else
  719. node = asNEW(asSMapNode_t);
  720. node->Init(obj, it);
  721. return node;
  722. }
  723. void asCGarbageCollector::ReturnNode(asSMapNode_t *node)
  724. {
  725. if( node )
  726. freeNodes.PushLast(node);
  727. }
  728. void asCGarbageCollector::GCEnumCallback(void *reference)
  729. {
  730. if( detectState == countReferences_loop )
  731. {
  732. // Find the reference in the map
  733. asSMapNode<void*, asSIntTypePair> *cursor = 0;
  734. if( gcMap.MoveTo(&cursor, reference) )
  735. {
  736. // Decrease the counter in the map for the reference
  737. gcMap.GetValue(cursor).i--;
  738. }
  739. }
  740. else if( detectState == detectGarbage_loop2 )
  741. {
  742. // Find the reference in the map
  743. asSMapNode<void*, asSIntTypePair> *cursor = 0;
  744. if( gcMap.MoveTo(&cursor, reference) )
  745. {
  746. // Add the object to the list of objects to mark as alive
  747. liveObjects.PushLast(reference);
  748. }
  749. }
  750. }
  751. END_AS_NAMESPACE