as_gc.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2010 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. BEGIN_AS_NAMESPACE
  33. asCGarbageCollector::asCGarbageCollector()
  34. {
  35. engine = 0;
  36. detectState = clearCounters_init;
  37. destroyState = destroyGarbage_init;
  38. numDestroyed = 0;
  39. numDetected = 0;
  40. }
  41. void asCGarbageCollector::AddScriptObjectToGC(void *obj, asCObjectType *objType)
  42. {
  43. engine->CallObjectMethod(obj, objType->beh.addref);
  44. asSObjTypePair ot = {obj, objType};
  45. // Add the data to the gcObjects array in a critical section as
  46. // another thread might be calling this method at the same time
  47. ENTERCRITICALSECTION(gcCritical);
  48. gcObjects.PushLast(ot);
  49. LEAVECRITICALSECTION(gcCritical);
  50. }
  51. int asCGarbageCollector::GarbageCollect(asDWORD flags)
  52. {
  53. // The application is responsible for making sure
  54. // the gc is only executed by one thread at a time.
  55. bool doDetect = (flags & asGC_DETECT_GARBAGE) || !(flags & asGC_DESTROY_GARBAGE);
  56. bool doDestroy = (flags & asGC_DESTROY_GARBAGE) || !(flags & asGC_DETECT_GARBAGE);
  57. if( flags & asGC_FULL_CYCLE )
  58. {
  59. // Reset the state
  60. if( doDetect )
  61. detectState = clearCounters_init;
  62. if( doDestroy )
  63. destroyState = destroyGarbage_init;
  64. int r = 1;
  65. unsigned int count = (unsigned int)gcObjects.GetLength();
  66. for(;;)
  67. {
  68. // Detect all garbage with cyclic references
  69. if( doDetect )
  70. while( (r = IdentifyGarbageWithCyclicRefs()) == 1 );
  71. // Now destroy all known garbage
  72. if( doDestroy )
  73. while( (r = DestroyGarbage()) == 1 );
  74. // Run another iteration if any garbage was destroyed
  75. if( count != gcObjects.GetLength() )
  76. count = (unsigned int)gcObjects.GetLength();
  77. else
  78. break;
  79. }
  80. // Take the opportunity to clear unused types as well
  81. engine->ClearUnusedTypes();
  82. return 0;
  83. }
  84. else
  85. {
  86. // Destroy the garbage that we know of
  87. if( doDestroy )
  88. DestroyGarbage();
  89. // Run another incremental step of the identification of cyclic references
  90. if( doDetect )
  91. IdentifyGarbageWithCyclicRefs();
  92. }
  93. // Return 1 to indicate that the cycle wasn't finished
  94. return 1;
  95. }
  96. void asCGarbageCollector::GetStatistics(asUINT *currentSize, asUINT *totalDestroyed, asUINT *totalDetected) const
  97. {
  98. // It's not necessary to protect this access, as
  99. // it doesn't matter if another thread is currently
  100. // appending a new object.
  101. if( currentSize )
  102. *currentSize = (asUINT)gcObjects.GetLength();
  103. if( totalDestroyed )
  104. *totalDestroyed = numDestroyed;
  105. if( totalDetected )
  106. *totalDetected = numDetected;
  107. }
  108. void asCGarbageCollector::ClearMap()
  109. {
  110. // Decrease reference counter for all objects removed from the map
  111. asSMapNode<void*, asSIntTypePair> *cursor = 0;
  112. gcMap.MoveFirst(&cursor);
  113. while( cursor )
  114. {
  115. void *obj = gcMap.GetKey(cursor);
  116. asSIntTypePair it = gcMap.GetValue(cursor);
  117. engine->CallObjectMethod(obj, it.type->beh.release);
  118. gcMap.MoveNext(&cursor, cursor);
  119. }
  120. gcMap.EraseAll();
  121. }
  122. asCGarbageCollector::asSObjTypePair asCGarbageCollector::GetObjectAtIdx(int idx)
  123. {
  124. // We need to protect this access with a critical section as
  125. // another thread might be appending an object at the same time
  126. ENTERCRITICALSECTION(gcCritical);
  127. asSObjTypePair gcObj = gcObjects[idx];
  128. LEAVECRITICALSECTION(gcCritical);
  129. return gcObj;
  130. }
  131. void asCGarbageCollector::RemoveObjectAtIdx(int idx)
  132. {
  133. // We need to protect this update with a critical section as
  134. // another thread might be appending an object at the same time
  135. ENTERCRITICALSECTION(gcCritical);
  136. if( idx == (int)gcObjects.GetLength() - 1)
  137. gcObjects.PopLast();
  138. else
  139. gcObjects[idx] = gcObjects.PopLast();
  140. LEAVECRITICALSECTION(gcCritical);
  141. }
  142. int asCGarbageCollector::DestroyGarbage()
  143. {
  144. for(;;)
  145. {
  146. switch( destroyState )
  147. {
  148. case destroyGarbage_init:
  149. {
  150. // If there are no objects to be freed then don't start
  151. if( gcObjects.GetLength() == 0 )
  152. return 0;
  153. destroyIdx = (asUINT)-1;
  154. destroyState = destroyGarbage_loop;
  155. }
  156. break;
  157. case destroyGarbage_loop:
  158. case destroyGarbage_haveMore:
  159. {
  160. // If the refCount has reached 1, then only the GC still holds a
  161. // reference to the object, thus we don't need to worry about the
  162. // application touching the objects during collection.
  163. // Destroy all objects that have refCount == 1. If any objects are
  164. // destroyed, go over the list again, because it may have made more
  165. // objects reach refCount == 1.
  166. while( ++destroyIdx < gcObjects.GetLength() )
  167. {
  168. asSObjTypePair gcObj = GetObjectAtIdx(destroyIdx);
  169. if( engine->CallObjectMethodRetInt(gcObj.obj, gcObj.type->beh.gcGetRefCount) == 1 )
  170. {
  171. // Release the object immediately
  172. // Make sure the refCount is really 0, because the
  173. // destructor may have increased the refCount again.
  174. bool addRef = false;
  175. if( gcObj.type->flags & asOBJ_SCRIPT_OBJECT )
  176. {
  177. // Script objects may actually be resurrected in the destructor
  178. int refCount = ((asCScriptObject*)gcObj.obj)->Release();
  179. if( refCount > 0 ) addRef = true;
  180. }
  181. else
  182. engine->CallObjectMethod(gcObj.obj, gcObj.type->beh.release);
  183. // Was the object really destroyed?
  184. if( !addRef )
  185. {
  186. numDestroyed++;
  187. RemoveObjectAtIdx(destroyIdx);
  188. destroyIdx--;
  189. }
  190. else
  191. {
  192. // Since the object was resurrected in the
  193. // destructor, we must add our reference again
  194. engine->CallObjectMethod(gcObj.obj, gcObj.type->beh.addref);
  195. }
  196. destroyState = destroyGarbage_haveMore;
  197. // Allow the application to work a little
  198. return 1;
  199. }
  200. }
  201. if( destroyState == destroyGarbage_haveMore )
  202. {
  203. // Restart the cycle
  204. destroyState = destroyGarbage_init;
  205. }
  206. else
  207. {
  208. // Restart the cycle
  209. destroyState = destroyGarbage_init;
  210. // Return 0 to tell the application that there
  211. // is no more garbage to destroy at the moment
  212. return 0;
  213. }
  214. }
  215. break;
  216. }
  217. }
  218. // Shouldn't reach this point
  219. UNREACHABLE_RETURN;
  220. }
  221. int asCGarbageCollector::IdentifyGarbageWithCyclicRefs()
  222. {
  223. for(;;)
  224. {
  225. switch( detectState )
  226. {
  227. case clearCounters_init:
  228. {
  229. ClearMap();
  230. detectState = clearCounters_loop;
  231. detectIdx = 0;
  232. }
  233. break;
  234. case clearCounters_loop:
  235. {
  236. // Build a map of objects that will be checked, the map will
  237. // hold the object pointer as key, and the gcCount and the
  238. // object's type as value. As objects are added to the map the
  239. // gcFlag must be set in the objects, so we can be verify if
  240. // the object is accessed during the GC cycle.
  241. // If an object is removed from the gcObjects list during the
  242. // iteration of this step, it is possible that an object won't
  243. // be used during the analyzing for cyclic references. This
  244. // isn't a problem, as the next time the GC cycle starts the
  245. // object will be verified.
  246. while( detectIdx < gcObjects.GetLength() )
  247. {
  248. // Add the gc count for this object
  249. asSObjTypePair gcObj = GetObjectAtIdx(detectIdx);
  250. int refCount = engine->CallObjectMethodRetInt(gcObj.obj, gcObj.type->beh.gcGetRefCount);
  251. if( refCount > 1 )
  252. {
  253. asSIntTypePair it = {refCount-1, gcObj.type};
  254. gcMap.Insert(gcObj.obj, it);
  255. // Increment the object's reference counter when putting it in the map
  256. engine->CallObjectMethod(gcObj.obj, gcObj.type->beh.addref);
  257. // Mark the object so that we can
  258. // see if it has changed since read
  259. engine->CallObjectMethod(gcObj.obj, gcObj.type->beh.gcSetFlag);
  260. detectIdx++;
  261. // Let the application work a little
  262. return 1;
  263. }
  264. else
  265. detectIdx++;
  266. }
  267. detectState = countReferences_init;
  268. }
  269. break;
  270. case countReferences_init:
  271. {
  272. detectIdx = (asUINT)-1;
  273. gcMap.MoveFirst(&gcMapCursor);
  274. detectState = countReferences_loop;
  275. }
  276. break;
  277. case countReferences_loop:
  278. {
  279. // Call EnumReferences on all objects in the map to count the number
  280. // of references reachable from between objects in the map. If all
  281. // references for an object in the map is reachable from other objects
  282. // in the map, then we know that no outside references are held for
  283. // this object, thus it is a potential dead object in a circular reference.
  284. // If the gcFlag is cleared for an object we consider the object alive
  285. // and referenced from outside the GC, thus we don't enumerate its references.
  286. // Any new objects created after this step in the GC cycle won't be
  287. // in the map, and is thus automatically considered alive.
  288. while( gcMapCursor )
  289. {
  290. void *obj = gcMap.GetKey(gcMapCursor);
  291. asCObjectType *type = gcMap.GetValue(gcMapCursor).type;
  292. gcMap.MoveNext(&gcMapCursor, gcMapCursor);
  293. if( engine->CallObjectMethodRetBool(obj, type->beh.gcGetFlag) )
  294. {
  295. engine->CallObjectMethod(obj, engine, type->beh.gcEnumReferences);
  296. // Allow the application to work a little
  297. return 1;
  298. }
  299. }
  300. detectState = detectGarbage_init;
  301. }
  302. break;
  303. case detectGarbage_init:
  304. {
  305. detectIdx = (asUINT)-1;
  306. gcMap.MoveFirst(&gcMapCursor);
  307. liveObjects.SetLength(0);
  308. detectState = detectGarbage_loop1;
  309. }
  310. break;
  311. case detectGarbage_loop1:
  312. {
  313. // All objects that are known not to be dead must be removed from the map,
  314. // along with all objects they reference. What remains in the map after
  315. // this pass is sure to be dead objects in circular references.
  316. // An object is considered alive if its gcFlag is cleared, or all the
  317. // references were not found in the map.
  318. // Add all alive objects from the map to the liveObjects array
  319. while( gcMapCursor )
  320. {
  321. asSMapNode<void*, asSIntTypePair> *cursor = gcMapCursor;
  322. gcMap.MoveNext(&gcMapCursor, gcMapCursor);
  323. void *obj = gcMap.GetKey(cursor);
  324. asSIntTypePair it = gcMap.GetValue(cursor);
  325. bool gcFlag = engine->CallObjectMethodRetBool(obj, it.type->beh.gcGetFlag);
  326. if( !gcFlag || it.i > 0 )
  327. {
  328. liveObjects.PushLast(obj);
  329. // Allow the application to work a little
  330. return 1;
  331. }
  332. }
  333. detectState = detectGarbage_loop2;
  334. }
  335. break;
  336. case detectGarbage_loop2:
  337. {
  338. // In this step we are actually removing the alive objects from the map.
  339. // As the object is removed, all the objects it references are added to the
  340. // liveObjects list, by calling EnumReferences. Only objects still in the map
  341. // will be added to the liveObjects list.
  342. while( liveObjects.GetLength() )
  343. {
  344. void *gcObj = liveObjects.PopLast();
  345. asCObjectType *type = 0;
  346. // Remove the object from the map to mark it as alive
  347. asSMapNode<void*, asSIntTypePair> *cursor = 0;
  348. if( gcMap.MoveTo(&cursor, gcObj) )
  349. {
  350. type = gcMap.GetValue(cursor).type;
  351. gcMap.Erase(cursor);
  352. // We need to decrease the reference count again as we remove the object from the map
  353. engine->CallObjectMethod(gcObj, type->beh.release);
  354. // Enumerate all the object's references so that they too can be marked as alive
  355. engine->CallObjectMethod(gcObj, engine, type->beh.gcEnumReferences);
  356. }
  357. // Allow the application to work a little
  358. return 1;
  359. }
  360. detectState = verifyUnmarked;
  361. }
  362. break;
  363. case verifyUnmarked:
  364. {
  365. // In this step we must make sure that none of the objects still in the map
  366. // has been touched by the application. If they have then we must run the
  367. // detectGarbage loop once more.
  368. gcMap.MoveFirst(&gcMapCursor);
  369. while( gcMapCursor )
  370. {
  371. void *gcObj = gcMap.GetKey(gcMapCursor);
  372. asCObjectType *type = gcMap.GetValue(gcMapCursor).type;
  373. bool gcFlag = engine->CallObjectMethodRetBool(gcObj, type->beh.gcGetFlag);
  374. if( !gcFlag )
  375. {
  376. // The unmarked object was touched, rerun the detectGarbage loop
  377. detectState = detectGarbage_init;
  378. return 1;
  379. }
  380. gcMap.MoveNext(&gcMapCursor, gcMapCursor);
  381. }
  382. // No unmarked object was touched, we can now be sure
  383. // that objects that have gcCount == 0 really is garbage
  384. detectState = breakCircles_init;
  385. }
  386. break;
  387. case breakCircles_init:
  388. {
  389. detectIdx = (asUINT)-1;
  390. gcMap.MoveFirst(&gcMapCursor);
  391. detectState = breakCircles_loop;
  392. }
  393. break;
  394. case breakCircles_loop:
  395. case breakCircles_haveGarbage:
  396. {
  397. // All objects in the map are now known to be dead objects
  398. // kept alive through circular references. To be able to free
  399. // these objects we need to force the breaking of the circle
  400. // by having the objects release their references.
  401. while( gcMapCursor )
  402. {
  403. numDetected++;
  404. void *gcObj = gcMap.GetKey(gcMapCursor);
  405. asCObjectType *type = gcMap.GetValue(gcMapCursor).type;
  406. engine->CallObjectMethod(gcObj, engine, type->beh.gcReleaseAllReferences);
  407. gcMap.MoveNext(&gcMapCursor, gcMapCursor);
  408. detectState = breakCircles_haveGarbage;
  409. // Allow the application to work a little
  410. return 1;
  411. }
  412. // If no garbage was detected we can finish now
  413. if( detectState != breakCircles_haveGarbage )
  414. {
  415. // Restart the GC
  416. detectState = clearCounters_init;
  417. return 0;
  418. }
  419. else
  420. {
  421. // Restart the GC
  422. detectState = clearCounters_init;
  423. return 1;
  424. }
  425. }
  426. break;
  427. } // switch
  428. }
  429. // Shouldn't reach this point
  430. UNREACHABLE_RETURN;
  431. }
  432. void asCGarbageCollector::GCEnumCallback(void *reference)
  433. {
  434. if( detectState == countReferences_loop )
  435. {
  436. // Find the reference in the map
  437. asSMapNode<void*, asSIntTypePair> *cursor = 0;
  438. if( gcMap.MoveTo(&cursor, reference) )
  439. {
  440. // Decrease the counter in the map for the reference
  441. gcMap.GetValue(cursor).i--;
  442. }
  443. }
  444. else if( detectState == detectGarbage_loop2 )
  445. {
  446. // Find the reference in the map
  447. asSMapNode<void*, asSIntTypePair> *cursor = 0;
  448. if( gcMap.MoveTo(&cursor, reference) )
  449. {
  450. // Add the object to the list of objects to mark as alive
  451. liveObjects.PushLast(reference);
  452. }
  453. }
  454. }
  455. END_AS_NAMESPACE