as_gc.cpp 23 KB

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