as_gc.cpp 29 KB

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