/xbmc/visualizations/Vortex/angelscript/angelscript/source/as_gc.cpp

http://github.com/xbmc/xbmc · C++ · 536 lines · 324 code · 82 blank · 130 comment · 57 complexity · ab44432e4c15bb30577f421232483bde MD5 · raw file

  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2009 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. 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)
  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. // Only move to the next step if no garbage was detected in this step
  202. if( destroyState == destroyGarbage_haveMore )
  203. destroyState = destroyGarbage_init;
  204. else
  205. return 0;
  206. }
  207. break;
  208. }
  209. }
  210. // Shouldn't reach this point
  211. UNREACHABLE_RETURN;
  212. }
  213. int asCGarbageCollector::IdentifyGarbageWithCyclicRefs()
  214. {
  215. for(;;)
  216. {
  217. switch( detectState )
  218. {
  219. case clearCounters_init:
  220. {
  221. ClearMap();
  222. detectState = clearCounters_loop;
  223. detectIdx = 0;
  224. }
  225. break;
  226. case clearCounters_loop:
  227. {
  228. // Build a map of objects that will be checked, the map will
  229. // hold the object pointer as key, and the gcCount and the
  230. // object's type as value. As objects are added to the map the
  231. // gcFlag must be set in the objects, so we can be verify if
  232. // the object is accessed during the GC cycle.
  233. // If an object is removed from the gcObjects list during the
  234. // iteration of this step, it is possible that an object won't
  235. // be used during the analyzing for cyclic references. This
  236. // isn't a problem, as the next time the GC cycle starts the
  237. // object will be verified.
  238. while( detectIdx < gcObjects.GetLength() )
  239. {
  240. // Add the gc count for this object
  241. asSObjTypePair gcObj = GetObjectAtIdx(detectIdx);
  242. int refCount = engine->CallObjectMethodRetInt(gcObj.obj, gcObj.type->beh.gcGetRefCount);
  243. if( refCount > 1 )
  244. {
  245. asSIntTypePair it = {refCount-1, gcObj.type};
  246. gcMap.Insert(gcObj.obj, it);
  247. // Increment the object's reference counter when putting it in the map
  248. engine->CallObjectMethod(gcObj.obj, gcObj.type->beh.addref);
  249. // Mark the object so that we can
  250. // see if it has changed since read
  251. engine->CallObjectMethod(gcObj.obj, gcObj.type->beh.gcSetFlag);
  252. detectIdx++;
  253. // Let the application work a little
  254. return 1;
  255. }
  256. else
  257. detectIdx++;
  258. }
  259. detectState = countReferences_init;
  260. }
  261. break;
  262. case countReferences_init:
  263. {
  264. detectIdx = (asUINT)-1;
  265. gcMap.MoveFirst(&gcMapCursor);
  266. detectState = countReferences_loop;
  267. }
  268. break;
  269. case countReferences_loop:
  270. {
  271. // Call EnumReferences on all objects in the map to count the number
  272. // of references reachable from between objects in the map. If all
  273. // references for an object in the map is reachable from other objects
  274. // in the map, then we know that no outside references are held for
  275. // this object, thus it is a potential dead object in a circular reference.
  276. // If the gcFlag is cleared for an object we consider the object alive
  277. // and referenced from outside the GC, thus we don't enumerate its references.
  278. // Any new objects created after this step in the GC cycle won't be
  279. // in the map, and is thus automatically considered alive.
  280. while( gcMapCursor )
  281. {
  282. void *obj = gcMap.GetKey(gcMapCursor);
  283. asCObjectType *type = gcMap.GetValue(gcMapCursor).type;
  284. gcMap.MoveNext(&gcMapCursor, gcMapCursor);
  285. if( engine->CallObjectMethodRetBool(obj, type->beh.gcGetFlag) )
  286. {
  287. engine->CallObjectMethod(obj, engine, type->beh.gcEnumReferences);
  288. // Allow the application to work a little
  289. return 1;
  290. }
  291. }
  292. detectState = detectGarbage_init;
  293. }
  294. break;
  295. case detectGarbage_init:
  296. {
  297. detectIdx = (asUINT)-1;
  298. gcMap.MoveFirst(&gcMapCursor);
  299. liveObjects.SetLength(0);
  300. detectState = detectGarbage_loop1;
  301. }
  302. break;
  303. case detectGarbage_loop1:
  304. {
  305. // All objects that are known not to be dead must be removed from the map,
  306. // along with all objects they reference. What remains in the map after
  307. // this pass is sure to be dead objects in circular references.
  308. // An object is considered alive if its gcFlag is cleared, or all the
  309. // references were not found in the map.
  310. // Add all alive objects from the map to the liveObjects array
  311. while( gcMapCursor )
  312. {
  313. asSMapNode<void*, asSIntTypePair> *cursor = gcMapCursor;
  314. gcMap.MoveNext(&gcMapCursor, gcMapCursor);
  315. void *obj = gcMap.GetKey(cursor);
  316. asSIntTypePair it = gcMap.GetValue(cursor);
  317. bool gcFlag = engine->CallObjectMethodRetBool(obj, it.type->beh.gcGetFlag);
  318. if( !gcFlag || it.i > 0 )
  319. {
  320. liveObjects.PushLast(obj);
  321. // Allow the application to work a little
  322. return 1;
  323. }
  324. }
  325. detectState = detectGarbage_loop2;
  326. }
  327. break;
  328. case detectGarbage_loop2:
  329. {
  330. // In this step we are actually removing the alive objects from the map.
  331. // As the object is removed, all the objects it references are added to the
  332. // liveObjects list, by calling EnumReferences. Only objects still in the map
  333. // will be added to the liveObjects list.
  334. while( liveObjects.GetLength() )
  335. {
  336. void *gcObj = liveObjects.PopLast();
  337. asCObjectType *type = 0;
  338. // Remove the object from the map to mark it as alive
  339. asSMapNode<void*, asSIntTypePair> *cursor = 0;
  340. if( gcMap.MoveTo(&cursor, gcObj) )
  341. {
  342. type = gcMap.GetValue(cursor).type;
  343. gcMap.Erase(cursor);
  344. // We need to decrease the reference count again as we remove the object from the map
  345. engine->CallObjectMethod(gcObj, type->beh.release);
  346. // Enumerate all the object's references so that they too can be marked as alive
  347. engine->CallObjectMethod(gcObj, engine, type->beh.gcEnumReferences);
  348. }
  349. // Allow the application to work a little
  350. return 1;
  351. }
  352. detectState = verifyUnmarked;
  353. }
  354. break;
  355. case verifyUnmarked:
  356. {
  357. // In this step we must make sure that none of the objects still in the map
  358. // has been touched by the application. If they have then we must run the
  359. // detectGarbage loop once more.
  360. gcMap.MoveFirst(&gcMapCursor);
  361. while( gcMapCursor )
  362. {
  363. void *gcObj = gcMap.GetKey(gcMapCursor);
  364. asCObjectType *type = gcMap.GetValue(gcMapCursor).type;
  365. bool gcFlag = engine->CallObjectMethodRetBool(gcObj, type->beh.gcGetFlag);
  366. if( !gcFlag )
  367. {
  368. // The unmarked object was touched, rerun the detectGarbage loop
  369. detectState = detectGarbage_init;
  370. return 1;
  371. }
  372. gcMap.MoveNext(&gcMapCursor, gcMapCursor);
  373. }
  374. // No unmarked object was touched, we can now be sure
  375. // that objects that have gcCount == 0 really is garbage
  376. detectState = breakCircles_init;
  377. }
  378. break;
  379. case breakCircles_init:
  380. {
  381. detectIdx = (asUINT)-1;
  382. gcMap.MoveFirst(&gcMapCursor);
  383. detectState = breakCircles_loop;
  384. }
  385. break;
  386. case breakCircles_loop:
  387. case breakCircles_haveGarbage:
  388. {
  389. // All objects in the map are now known to be dead objects
  390. // kept alive through circular references. To be able to free
  391. // these objects we need to force the breaking of the circle
  392. // by having the objects release their references.
  393. while( gcMapCursor )
  394. {
  395. numDetected++;
  396. void *gcObj = gcMap.GetKey(gcMapCursor);
  397. asCObjectType *type = gcMap.GetValue(gcMapCursor).type;
  398. engine->CallObjectMethod(gcObj, engine, type->beh.gcReleaseAllReferences);
  399. gcMap.MoveNext(&gcMapCursor, gcMapCursor);
  400. detectState = breakCircles_haveGarbage;
  401. // Allow the application to work a little
  402. return 1;
  403. }
  404. // If no garbage was detected we can finish now
  405. if( detectState != breakCircles_haveGarbage )
  406. {
  407. // Restart the GC
  408. detectState = clearCounters_init;
  409. return 0;
  410. }
  411. else
  412. {
  413. // Restart the GC
  414. detectState = clearCounters_init;
  415. return 1;
  416. }
  417. }
  418. break;
  419. } // switch
  420. }
  421. // Shouldn't reach this point
  422. UNREACHABLE_RETURN;
  423. }
  424. void asCGarbageCollector::GCEnumCallback(void *reference)
  425. {
  426. if( detectState == countReferences_loop )
  427. {
  428. // Find the reference in the map
  429. asSMapNode<void*, asSIntTypePair> *cursor = 0;
  430. if( gcMap.MoveTo(&cursor, reference) )
  431. {
  432. // Decrease the counter in the map for the reference
  433. gcMap.GetValue(cursor).i--;
  434. }
  435. }
  436. else if( detectState == detectGarbage_loop2 )
  437. {
  438. // Find the reference in the map
  439. asSMapNode<void*, asSIntTypePair> *cursor = 0;
  440. if( gcMap.MoveTo(&cursor, reference) )
  441. {
  442. // Add the object to the list of objects to mark as alive
  443. liveObjects.PushLast(reference);
  444. }
  445. }
  446. }
  447. END_AS_NAMESPACE