as_gc.cpp 27 KB

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