as_gc.cpp 23 KB

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