as_gc.cpp 28 KB

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