as_gc.cpp 23 KB

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