as_gc.cpp 30 KB

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