as_gc.cpp 29 KB

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