lgc.c 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  1. /*
  2. ** $Id: lgc.c,v 2.167 2013/12/13 15:17:00 roberto Exp roberto $
  3. ** Garbage Collector
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <string.h>
  7. #define lgc_c
  8. #define LUA_CORE
  9. #include "lua.h"
  10. #include "ldebug.h"
  11. #include "ldo.h"
  12. #include "lfunc.h"
  13. #include "lgc.h"
  14. #include "lmem.h"
  15. #include "lobject.h"
  16. #include "lstate.h"
  17. #include "lstring.h"
  18. #include "ltable.h"
  19. #include "ltm.h"
  20. /*
  21. ** cost of sweeping one element (the size of a small object divided
  22. ** by some adjust for the sweep speed)
  23. */
  24. #define GCSWEEPCOST ((sizeof(TString) + 4) / 4)
  25. /* maximum number of elements to sweep in each single step */
  26. #define GCSWEEPMAX (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4))
  27. /* maximum number of finalizers to call in each GC step */
  28. #define GCFINALIZENUM 4
  29. /*
  30. ** macro to adjust 'stepmul': 'stepmul' is actually used like
  31. ** 'stepmul / STEPMULADJ' (value chosen by tests)
  32. */
  33. #define STEPMULADJ 200
  34. /*
  35. ** macro to adjust 'pause': 'pause' is actually used like
  36. ** 'pause / PAUSEADJ' (value chosen by tests)
  37. */
  38. #define PAUSEADJ 100
  39. /*
  40. ** 'makewhite' erases all color bits then sets only the current white
  41. ** bit
  42. */
  43. #define maskcolors (~(bitmask(BLACKBIT) | WHITEBITS))
  44. #define makewhite(g,x) \
  45. (gch(x)->marked = cast_byte((gch(x)->marked & maskcolors) | luaC_white(g)))
  46. #define white2gray(x) resetbits(gch(x)->marked, WHITEBITS)
  47. #define black2gray(x) resetbit(gch(x)->marked, BLACKBIT)
  48. #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
  49. #define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))
  50. #define checkconsistency(obj) \
  51. lua_longassert(!iscollectable(obj) || righttt(obj))
  52. #define marklocalvalue(g,o) { checkconsistency(o); \
  53. if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
  54. #define markvalue(g,o) { \
  55. lua_longassert(!(iscollectable(o) && islocal(gcvalue(o)))); \
  56. marklocalvalue(g,o); }
  57. #define marklocalobject(g,t) \
  58. { if ((t) && iswhite(obj2gco(t))) reallymarkobject(g, obj2gco(t)); }
  59. #define markobject(g,t) \
  60. { lua_assert((t) == NULL || !islocal(obj2gco(t))); marklocalobject(g,t); }
  61. static void reallymarkobject (global_State *g, GCObject *o);
  62. /*
  63. ** {======================================================
  64. ** Generic functions
  65. ** =======================================================
  66. */
  67. /*
  68. ** one after last element in a hash array
  69. */
  70. #define gnodelast(h) gnode(h, cast(size_t, sizenode(h)))
  71. /*
  72. ** link table 'h' into list pointed by 'p'
  73. */
  74. #define linktable(h,p) ((h)->gclist = *(p), *(p) = obj2gco(h))
  75. /*
  76. ** if key is not marked, mark its entry as dead (therefore removing it
  77. ** from the table)
  78. */
  79. static void removeentry (Node *n) {
  80. lua_assert(ttisnil(gval(n)));
  81. if (valiswhite(gkey(n)))
  82. setdeadvalue(gkey(n)); /* unused and unmarked key; remove it */
  83. }
  84. /*
  85. ** tells whether a key or value can be cleared from a weak
  86. ** table. Non-collectable objects are never removed from weak
  87. ** tables. Strings behave as `values', so are never removed too. for
  88. ** other objects: if really collected, cannot keep them; for objects
  89. ** being finalized, keep them in keys, but not in values
  90. */
  91. static int iscleared (global_State *g, const TValue *o) {
  92. if (!iscollectable(o)) return 0;
  93. else if (ttisstring(o)) {
  94. markobject(g, rawtsvalue(o)); /* strings are `values', so are never weak */
  95. return 0;
  96. }
  97. else return iswhite(gcvalue(o));
  98. }
  99. /*
  100. ** barrier that moves collector forward, that is, mark the white object
  101. ** being pointed by a black object.
  102. */
  103. void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
  104. global_State *g = G(L);
  105. lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
  106. lua_assert(g->gcstate != GCSpause);
  107. lua_assert(gch(o)->tt != LUA_TTABLE); /* tables use a back barrier */
  108. if (keepinvariant(g)) /* must keep invariant? */
  109. reallymarkobject(g, v); /* restore invariant */
  110. else { /* sweep phase */
  111. lua_assert(issweepphase(g));
  112. makewhite(g, o); /* mark main obj. as white to avoid other barriers */
  113. }
  114. }
  115. /*
  116. ** barrier that moves collector backward, that is, mark the black object
  117. ** pointing to a white object as gray again. (Current implementation
  118. ** only works for tables; access to 'gclist' is not uniform across
  119. ** different types.)
  120. */
  121. void luaC_barrierback_ (lua_State *L, GCObject *o) {
  122. global_State *g = G(L);
  123. lua_assert(isblack(o) && !isdead(g, o) && gch(o)->tt == LUA_TTABLE);
  124. black2gray(o); /* make object gray (again) */
  125. gco2t(o)->gclist = g->grayagain;
  126. g->grayagain = o;
  127. }
  128. /*
  129. ** barrier for assignments to closed upvalues. Because upvalues are
  130. ** shared among closures, it is impossible to know the color of all
  131. ** closured pointing to it. So, we assume that the object being assigned
  132. ** must be marked.
  133. */
  134. LUAI_FUNC void luaC_upvalbarrier_ (lua_State *L, UpVal *uv) {
  135. global_State *g = G(L);
  136. GCObject *o = gcvalue(uv->v);
  137. lua_assert(!upisopen(uv)); /* ensured by macro luaC_upvalbarrier */
  138. nolocal(o);
  139. if (keepinvariant(g))
  140. markobject(g, o);
  141. }
  142. void luaC_fix (lua_State *L, GCObject *o) {
  143. global_State *g = G(L);
  144. lua_assert(g->localgc == o);
  145. white2gray(o);
  146. g->localgc = o->gch.next; /* remove object from 'localgc' list */
  147. o->gch.next = g->fixedgc; /* link it to 'fixedgc' list */
  148. g->fixedgc = o;
  149. }
  150. /*
  151. ** create a new collectable object (with given type and size) and link
  152. ** it to 'localgc' list.
  153. */
  154. GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
  155. global_State *g = G(L);
  156. GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz));
  157. gch(o)->marked = luaC_white(g);
  158. gch(o)->tt = tt;
  159. gch(o)->next = g->localgc;
  160. g->localgc = o;
  161. return o;
  162. }
  163. /* }====================================================== */
  164. /*
  165. ** {======================================================
  166. ** Mark functions
  167. ** =======================================================
  168. */
  169. /*
  170. ** mark an object. Userdata, strings, and closed upvalues are visited
  171. ** and turned black here. Other objects are marked gray and added
  172. ** to appropriate list to be visited (and turned black) later. (Open
  173. ** upvalues are already linked in 'headuv' list.)
  174. */
  175. static void reallymarkobject (global_State *g, GCObject *o) {
  176. reentry:
  177. white2gray(o);
  178. switch (gch(o)->tt) {
  179. case LUA_TSHRSTR:
  180. case LUA_TLNGSTR: {
  181. gray2black(o);
  182. g->GCmemtrav += sizestring(gco2ts(o));
  183. break;
  184. }
  185. case LUA_TUSERDATA: {
  186. markobject(g, gco2u(o)->metatable); /* mark its metatable */
  187. gray2black(o);
  188. g->GCmemtrav += sizeudata(gco2u(o));
  189. o = obj2gco(gco2u(o)->env);
  190. if (o && iswhite(o))
  191. goto reentry; /* reallymarkobject(g, gco2u(o)->env); */
  192. break;
  193. }
  194. case LUA_TLCL: {
  195. gco2lcl(o)->gclist = g->gray;
  196. g->gray = o;
  197. break;
  198. }
  199. case LUA_TCCL: {
  200. gco2ccl(o)->gclist = g->gray;
  201. g->gray = o;
  202. break;
  203. }
  204. case LUA_TTABLE: {
  205. linktable(gco2t(o), &g->gray);
  206. break;
  207. }
  208. case LUA_TTHREAD: {
  209. gco2th(o)->gclist = g->gray;
  210. g->gray = o;
  211. break;
  212. }
  213. case LUA_TPROTO: {
  214. gco2p(o)->gclist = g->gray;
  215. g->gray = o;
  216. break;
  217. }
  218. default: lua_assert(0); break;
  219. }
  220. }
  221. /*
  222. ** mark metamethods for basic types
  223. */
  224. static void markmt (global_State *g) {
  225. int i;
  226. for (i=0; i < LUA_NUMTAGS; i++)
  227. markobject(g, g->mt[i]);
  228. }
  229. /*
  230. ** mark all objects in list of being-finalized
  231. */
  232. static void markbeingfnz (global_State *g) {
  233. GCObject *o;
  234. for (o = g->tobefnz; o != NULL; o = gch(o)->next)
  235. marklocalobject(g, o);
  236. }
  237. /*
  238. ** Mark all values stored in marked open upvalues from non-marked threads.
  239. ** (Values from marked threads were already marked when traversing the
  240. ** thread.)
  241. */
  242. static void remarkupvals (global_State *g) {
  243. GCObject *thread = g->mainthread->next;
  244. for (; thread != NULL; thread = gch(thread)->next) {
  245. lua_assert(!isblack(thread)); /* threads are never black */
  246. if (!isgray(thread)) { /* dead thread? */
  247. UpVal *uv = gco2th(thread)->openupval;
  248. for (; uv != NULL; uv = uv->u.op.next) {
  249. if (uv->u.op.touched) {
  250. marklocalvalue(g, uv->v); /* remark upvalue's value */
  251. uv->u.op.touched = 0;
  252. }
  253. }
  254. }
  255. }
  256. }
  257. /*
  258. ** mark root set and reset all gray lists, to start a new collection
  259. */
  260. static void restartcollection (global_State *g) {
  261. g->gray = g->grayagain = NULL;
  262. g->weak = g->allweak = g->ephemeron = NULL;
  263. markobject(g, g->mainthread);
  264. markvalue(g, &g->l_registry);
  265. markmt(g);
  266. markbeingfnz(g); /* mark any finalizing object left from previous cycle */
  267. }
  268. /* }====================================================== */
  269. /*
  270. ** {======================================================
  271. ** Traverse functions
  272. ** =======================================================
  273. */
  274. static void traverseweakvalue (global_State *g, Table *h) {
  275. Node *n, *limit = gnodelast(h);
  276. /* if there is array part, assume it may have white values (do not
  277. traverse it just to check) */
  278. int hasclears = (h->sizearray > 0);
  279. for (n = gnode(h, 0); n < limit; n++) {
  280. checkdeadkey(n);
  281. if (ttisnil(gval(n))) /* entry is empty? */
  282. removeentry(n); /* remove it */
  283. else {
  284. lua_assert(!ttisnil(gkey(n)));
  285. markvalue(g, gkey(n)); /* mark key */
  286. if (!hasclears && iscleared(g, gval(n))) /* is there a white value? */
  287. hasclears = 1; /* table will have to be cleared */
  288. }
  289. }
  290. if (hasclears)
  291. linktable(h, &g->weak); /* has to be cleared later */
  292. else /* no white values */
  293. linktable(h, &g->grayagain); /* no need to clean */
  294. }
  295. static int traverseephemeron (global_State *g, Table *h) {
  296. int marked = 0; /* true if an object is marked in this traversal */
  297. int hasclears = 0; /* true if table has white keys */
  298. int prop = 0; /* true if table has entry "white-key -> white-value" */
  299. Node *n, *limit = gnodelast(h);
  300. int i;
  301. /* traverse array part (numeric keys are 'strong') */
  302. for (i = 0; i < h->sizearray; i++) {
  303. if (valiswhite(&h->array[i])) {
  304. marked = 1;
  305. reallymarkobject(g, gcvalue(&h->array[i]));
  306. }
  307. }
  308. /* traverse hash part */
  309. for (n = gnode(h, 0); n < limit; n++) {
  310. checkdeadkey(n);
  311. if (ttisnil(gval(n))) /* entry is empty? */
  312. removeentry(n); /* remove it */
  313. else if (iscleared(g, gkey(n))) { /* key is not marked (yet)? */
  314. hasclears = 1; /* table must be cleared */
  315. if (valiswhite(gval(n))) /* value not marked yet? */
  316. prop = 1; /* must propagate again */
  317. }
  318. else if (valiswhite(gval(n))) { /* value not marked yet? */
  319. marked = 1;
  320. reallymarkobject(g, gcvalue(gval(n))); /* mark it now */
  321. }
  322. }
  323. if (prop)
  324. linktable(h, &g->ephemeron); /* have to propagate again */
  325. else if (hasclears) /* does table have white keys? */
  326. linktable(h, &g->allweak); /* may have to clean white keys */
  327. else /* no white keys */
  328. linktable(h, &g->grayagain); /* no need to clean */
  329. return marked;
  330. }
  331. static void traversestrongtable (global_State *g, Table *h) {
  332. Node *n, *limit = gnodelast(h);
  333. int i;
  334. for (i = 0; i < h->sizearray; i++) /* traverse array part */
  335. markvalue(g, &h->array[i]);
  336. for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
  337. checkdeadkey(n);
  338. if (ttisnil(gval(n))) /* entry is empty? */
  339. removeentry(n); /* remove it */
  340. else {
  341. lua_assert(!ttisnil(gkey(n)));
  342. markvalue(g, gkey(n)); /* mark key */
  343. markvalue(g, gval(n)); /* mark value */
  344. }
  345. }
  346. }
  347. static lu_mem traversetable (global_State *g, Table *h) {
  348. const char *weakkey, *weakvalue;
  349. const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
  350. markobject(g, h->metatable);
  351. if (mode && ttisstring(mode) && /* is there a weak mode? */
  352. ((weakkey = strchr(svalue(mode), 'k')),
  353. (weakvalue = strchr(svalue(mode), 'v')),
  354. (weakkey || weakvalue))) { /* is really weak? */
  355. black2gray(obj2gco(h)); /* keep table gray */
  356. if (!weakkey) /* strong keys? */
  357. traverseweakvalue(g, h);
  358. else if (!weakvalue) /* strong values? */
  359. traverseephemeron(g, h);
  360. else /* all weak */
  361. linktable(h, &g->allweak); /* nothing to traverse now */
  362. }
  363. else /* not weak */
  364. traversestrongtable(g, h);
  365. return sizeof(Table) + sizeof(TValue) * h->sizearray +
  366. sizeof(Node) * cast(size_t, sizenode(h));
  367. }
  368. static int traverseproto (global_State *g, Proto *f) {
  369. int i;
  370. if (f->cache && iswhite(obj2gco(f->cache)))
  371. f->cache = NULL; /* allow cache to be collected */
  372. markobject(g, f->source);
  373. for (i = 0; i < f->sizek; i++) /* mark literals */
  374. markvalue(g, &f->k[i]);
  375. for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
  376. markobject(g, f->upvalues[i].name);
  377. for (i = 0; i < f->sizep; i++) /* mark nested protos */
  378. markobject(g, f->p[i]);
  379. for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
  380. markobject(g, f->locvars[i].varname);
  381. return sizeof(Proto) + sizeof(Instruction) * f->sizecode +
  382. sizeof(Proto *) * f->sizep +
  383. sizeof(TValue) * f->sizek +
  384. sizeof(int) * f->sizelineinfo +
  385. sizeof(LocVar) * f->sizelocvars +
  386. sizeof(Upvaldesc) * f->sizeupvalues;
  387. }
  388. static lu_mem traverseCclosure (global_State *g, CClosure *cl) {
  389. int i;
  390. for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */
  391. marklocalvalue(g, &cl->upvalue[i]);
  392. return sizeCclosure(cl->nupvalues);
  393. }
  394. static lu_mem traverseLclosure (global_State *g, LClosure *cl) {
  395. int i;
  396. markobject(g, cl->p); /* mark its prototype */
  397. for (i = 0; i < cl->nupvalues; i++) { /* mark its upvalues */
  398. UpVal *uv = cl->upvals[i];
  399. if (uv != NULL) {
  400. if (upisopen(uv))
  401. uv->u.op.touched = 1; /* can be marked in 'remarkupvals' */
  402. else
  403. markvalue(g, uv->v);
  404. }
  405. }
  406. return sizeLclosure(cl->nupvalues);
  407. }
  408. static lu_mem traversestack (global_State *g, lua_State *th) {
  409. int n = 0;
  410. StkId o = th->stack;
  411. if (o == NULL)
  412. return 1; /* stack not completely built yet */
  413. for (; o < th->top; o++) /* mark live elements in the stack */
  414. marklocalvalue(g, o);
  415. if (g->gcstate == GCSatomic) { /* final traversal? */
  416. StkId lim = th->stack + th->stacksize; /* real end of stack */
  417. for (; o < lim; o++) /* clear not-marked stack slice */
  418. setnilvalue(o);
  419. }
  420. else {
  421. CallInfo *ci;
  422. for (ci = &th->base_ci; ci != th->ci; ci = ci->next)
  423. n++; /* count call infos to compute size */
  424. /* should not change the stack during an emergency gc cycle */
  425. if (g->gckind != KGC_EMERGENCY)
  426. luaD_shrinkstack(th);
  427. }
  428. return sizeof(lua_State) + sizeof(TValue) * th->stacksize +
  429. sizeof(CallInfo) * n;
  430. }
  431. /*
  432. ** traverse one gray object, turning it to black (except for threads,
  433. ** which are always gray).
  434. */
  435. static void propagatemark (global_State *g) {
  436. lu_mem size;
  437. GCObject *o = g->gray;
  438. lua_assert(isgray(o));
  439. gray2black(o);
  440. switch (gch(o)->tt) {
  441. case LUA_TTABLE: {
  442. Table *h = gco2t(o);
  443. g->gray = h->gclist; /* remove from 'gray' list */
  444. size = traversetable(g, h);
  445. break;
  446. }
  447. case LUA_TLCL: {
  448. LClosure *cl = gco2lcl(o);
  449. g->gray = cl->gclist; /* remove from 'gray' list */
  450. size = traverseLclosure(g, cl);
  451. break;
  452. }
  453. case LUA_TCCL: {
  454. CClosure *cl = gco2ccl(o);
  455. g->gray = cl->gclist; /* remove from 'gray' list */
  456. size = traverseCclosure(g, cl);
  457. break;
  458. }
  459. case LUA_TTHREAD: {
  460. lua_State *th = gco2th(o);
  461. g->gray = th->gclist; /* remove from 'gray' list */
  462. th->gclist = g->grayagain;
  463. g->grayagain = o; /* insert into 'grayagain' list */
  464. black2gray(o);
  465. size = traversestack(g, th);
  466. break;
  467. }
  468. case LUA_TPROTO: {
  469. Proto *p = gco2p(o);
  470. g->gray = p->gclist; /* remove from 'gray' list */
  471. size = traverseproto(g, p);
  472. break;
  473. }
  474. default: lua_assert(0); return;
  475. }
  476. g->GCmemtrav += size;
  477. }
  478. static void propagateall (global_State *g) {
  479. while (g->gray) propagatemark(g);
  480. }
  481. static void propagatelist (global_State *g, GCObject *l) {
  482. lua_assert(g->gray == NULL); /* no grays left */
  483. g->gray = l;
  484. propagateall(g); /* traverse all elements from 'l' */
  485. }
  486. /*
  487. ** retraverse all gray lists. Because tables may be reinserted in other
  488. ** lists when traversed, traverse the original lists to avoid traversing
  489. ** twice the same table (which is not wrong, but inefficient)
  490. */
  491. static void retraversegrays (global_State *g) {
  492. GCObject *weak = g->weak; /* save original lists */
  493. GCObject *grayagain = g->grayagain;
  494. GCObject *ephemeron = g->ephemeron;
  495. g->weak = g->grayagain = g->ephemeron = NULL;
  496. propagateall(g); /* traverse main gray list */
  497. propagatelist(g, grayagain);
  498. propagatelist(g, weak);
  499. propagatelist(g, ephemeron);
  500. }
  501. static void convergeephemerons (global_State *g) {
  502. int changed;
  503. do {
  504. GCObject *w;
  505. GCObject *next = g->ephemeron; /* get ephemeron list */
  506. g->ephemeron = NULL; /* tables will return to this list when traversed */
  507. changed = 0;
  508. while ((w = next) != NULL) {
  509. next = gco2t(w)->gclist;
  510. if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */
  511. propagateall(g); /* propagate changes */
  512. changed = 1; /* will have to revisit all ephemeron tables */
  513. }
  514. }
  515. } while (changed);
  516. }
  517. /* }====================================================== */
  518. /*
  519. ** {======================================================
  520. ** Sweep Functions
  521. ** =======================================================
  522. */
  523. /*
  524. ** clear entries with unmarked keys from all weaktables in list 'l' up
  525. ** to element 'f'
  526. */
  527. static void clearkeys (global_State *g, GCObject *l, GCObject *f) {
  528. for (; l != f; l = gco2t(l)->gclist) {
  529. Table *h = gco2t(l);
  530. Node *n, *limit = gnodelast(h);
  531. for (n = gnode(h, 0); n < limit; n++) {
  532. if (!ttisnil(gval(n)) && (iscleared(g, gkey(n)))) {
  533. setnilvalue(gval(n)); /* remove value ... */
  534. removeentry(n); /* and remove entry from table */
  535. }
  536. }
  537. }
  538. }
  539. /*
  540. ** clear entries with unmarked values from all weaktables in list 'l' up
  541. ** to element 'f'
  542. */
  543. static void clearvalues (global_State *g, GCObject *l, GCObject *f) {
  544. for (; l != f; l = gco2t(l)->gclist) {
  545. Table *h = gco2t(l);
  546. Node *n, *limit = gnodelast(h);
  547. int i;
  548. for (i = 0; i < h->sizearray; i++) {
  549. TValue *o = &h->array[i];
  550. if (iscleared(g, o)) /* value was collected? */
  551. setnilvalue(o); /* remove value */
  552. }
  553. for (n = gnode(h, 0); n < limit; n++) {
  554. if (!ttisnil(gval(n)) && iscleared(g, gval(n))) {
  555. setnilvalue(gval(n)); /* remove value ... */
  556. removeentry(n); /* and remove entry from table */
  557. }
  558. }
  559. }
  560. }
  561. void luaC_upvdeccount (lua_State *L, UpVal *uv) {
  562. lua_assert(uv->refcount > 0);
  563. uv->refcount--;
  564. if (uv->refcount == 0 && !upisopen(uv))
  565. luaM_free(L, uv);
  566. }
  567. static void freeLclosure (lua_State *L, LClosure *cl) {
  568. int i;
  569. for (i = 0; i < cl->nupvalues; i++) {
  570. UpVal *uv = cl->upvals[i];
  571. if (uv)
  572. luaC_upvdeccount(L, uv);
  573. }
  574. luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
  575. }
  576. static void freeobj (lua_State *L, GCObject *o) {
  577. switch (gch(o)->tt) {
  578. case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
  579. case LUA_TLCL: {
  580. freeLclosure(L, gco2lcl(o));
  581. break;
  582. }
  583. case LUA_TCCL: {
  584. luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));
  585. break;
  586. }
  587. case LUA_TTABLE: luaH_free(L, gco2t(o)); break;
  588. case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
  589. case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
  590. case LUA_TSHRSTR:
  591. luaS_remove(L, rawgco2ts(o)); /* remove it from hash table */
  592. /* go through */
  593. case LUA_TLNGSTR: {
  594. luaM_freemem(L, o, sizestring(gco2ts(o)));
  595. break;
  596. }
  597. default: lua_assert(0);
  598. }
  599. }
  600. #define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM)
  601. static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);
  602. /*
  603. ** sweep at most 'count' elements from a list of GCObjects erasing dead
  604. ** objects, where a dead (not alive) object is one marked with the "old"
  605. ** (non current) white and not fixed; change all non-dead objects back
  606. ** to white, preparing for next collection cycle.
  607. ** When object is a thread, sweep its list of open upvalues too.
  608. */
  609. static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
  610. global_State *g = G(L);
  611. int ow = otherwhite(g);
  612. int white = luaC_white(g); /* current white */
  613. while (*p != NULL && count-- > 0) {
  614. GCObject *curr = *p;
  615. int marked = gch(curr)->marked;
  616. if (isdeadm(ow, marked)) { /* is 'curr' dead? */
  617. *p = gch(curr)->next; /* remove 'curr' from list */
  618. freeobj(L, curr); /* erase 'curr' */
  619. }
  620. else { /* update marks */
  621. gch(curr)->marked = cast_byte((marked & maskcolors) | white);
  622. p = &gch(curr)->next; /* go to next element */
  623. }
  624. }
  625. return (*p == NULL) ? NULL : p;
  626. }
  627. /*
  628. ** sweep a list until a live object (or end of list)
  629. */
  630. static GCObject **sweeptolive (lua_State *L, GCObject **p, int *n) {
  631. GCObject **old = p;
  632. int i = 0;
  633. do {
  634. i++;
  635. p = sweeplist(L, p, 1);
  636. } while (p == old);
  637. if (n) *n += i;
  638. return p;
  639. }
  640. /* }====================================================== */
  641. /*
  642. ** {======================================================
  643. ** Finalization
  644. ** =======================================================
  645. */
  646. /*
  647. ** If possible, free concatenation buffer and shrink string table
  648. */
  649. static void checkSizes (lua_State *L, global_State *g) {
  650. if (g->gckind != KGC_EMERGENCY) {
  651. luaZ_freebuffer(L, &g->buff); /* free concatenation buffer */
  652. if (g->strt.nuse < g->strt.size / 4) /* string table too big? */
  653. luaS_resize(L, g->strt.size / 2); /* shrink it a little */
  654. }
  655. }
  656. static GCObject *udata2finalize (global_State *g) {
  657. GCObject *o = g->tobefnz; /* get first element */
  658. lua_assert(tofinalize(o));
  659. g->tobefnz = gch(o)->next; /* remove it from 'tobefnz' list */
  660. if (islocal(o)) {
  661. lua_assert(!testbit(gch(o)->marked, LOCALMARK));
  662. gch(o)->next = g->localgc; /* return it to 'localgc' list */
  663. g->localgc = o;
  664. }
  665. else { /* return it to 'allgc' list */
  666. gch(o)->next = g->allgc;
  667. g->allgc = o;
  668. l_setbit(gch(o)->marked, LOCALMARK);
  669. }
  670. resetbit(gch(o)->marked, FINALIZEDBIT); /* object is back in 'allgc' */
  671. if (issweepphase(g))
  672. makewhite(g, o); /* "sweep" object */
  673. return o;
  674. }
  675. static void dothecall (lua_State *L, void *ud) {
  676. UNUSED(ud);
  677. luaD_call(L, L->top - 2, 0, 0);
  678. }
  679. static void GCTM (lua_State *L, int propagateerrors) {
  680. global_State *g = G(L);
  681. const TValue *tm;
  682. TValue v;
  683. setgcovalue(L, &v, udata2finalize(g));
  684. tm = luaT_gettmbyobj(L, &v, TM_GC);
  685. if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */
  686. int status;
  687. lu_byte oldah = L->allowhook;
  688. int running = g->gcrunning;
  689. L->allowhook = 0; /* stop debug hooks during GC metamethod */
  690. g->gcrunning = 0; /* avoid GC steps */
  691. setobj2s(L, L->top, tm); /* push finalizer... */
  692. setobj2s(L, L->top + 1, &v); /* ... and its argument */
  693. L->top += 2; /* and (next line) call the finalizer */
  694. status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
  695. L->allowhook = oldah; /* restore hooks */
  696. g->gcrunning = running; /* restore state */
  697. if (status != LUA_OK && propagateerrors) { /* error while running __gc? */
  698. if (status == LUA_ERRRUN) { /* is there an error object? */
  699. const char *msg = (ttisstring(L->top - 1))
  700. ? svalue(L->top - 1)
  701. : "no message";
  702. luaO_pushfstring(L, "error in __gc metamethod (%s)", msg);
  703. status = LUA_ERRGCMM; /* error in __gc metamethod */
  704. }
  705. luaD_throw(L, status); /* re-throw error */
  706. }
  707. }
  708. }
  709. /*
  710. ** call all pending finalizers
  711. */
  712. static void callallpendingfinalizers (lua_State *L, int propagateerrors) {
  713. global_State *g = G(L);
  714. while (g->tobefnz)
  715. GCTM(L, propagateerrors);
  716. }
  717. /*
  718. ** find last 'next' field in list 'p' list (to add elements in its end)
  719. */
  720. static GCObject **findlast (GCObject **p) {
  721. while (*p != NULL)
  722. p = &gch(*p)->next;
  723. return p;
  724. }
  725. /*
  726. ** move all unreachable objects (or 'all' objects) that need
  727. ** finalization from list 'p' to list 'tobefnz' (to be finalized)
  728. */
  729. static void separatetobefnz_aux (global_State *g, GCObject **p, int all) {
  730. GCObject *curr;
  731. GCObject **lastnext = findlast(&g->tobefnz);
  732. while ((curr = *p) != NULL) { /* traverse all finalizable objects */
  733. lua_assert(tofinalize(curr));
  734. if (!(iswhite(curr) || all)) /* not being collected? */
  735. p = &gch(curr)->next; /* don't bother with it */
  736. else {
  737. *p = gch(curr)->next; /* remove 'curr' from "fin" list */
  738. gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */
  739. *lastnext = curr;
  740. lastnext = &gch(curr)->next;
  741. }
  742. }
  743. }
  744. static void separatetobefnz (global_State *g, int all) {
  745. separatetobefnz_aux(g, &g->localfin, all);
  746. separatetobefnz_aux(g, &g->finobj, all);
  747. }
  748. /*
  749. ** if object 'o' has a finalizer, remove it from 'allgc' list (must
  750. ** search the list to find it) and link it in 'localfin' or 'finobj' list.
  751. */
  752. void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
  753. global_State *g = G(L);
  754. if (tofinalize(o) || /* obj. is already marked... */
  755. gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */
  756. return; /* nothing to be done */
  757. else { /* move 'o' to 'finobj' list */
  758. GCObject **p;
  759. if (g->sweepgc == &o->gch.next) { /* avoid removing current sweep object */
  760. lua_assert(issweepphase(g));
  761. g->sweepgc = sweeptolive(L, g->sweepgc, NULL);
  762. }
  763. /* search for pointer pointing to 'o' */
  764. p = (testbit(o->gch.marked, LOCALMARK)) ? &g->allgc : &g->localgc;
  765. for (; *p != o; p = &gch(*p)->next) { /* empty */ }
  766. *p = o->gch.next; /* remove 'o' from its list */
  767. p = (testbit(o->gch.marked, LOCALMARK)) ? &g->finobj : &g->localfin;
  768. o->gch.next = *p; /* link it in a "fin" list */
  769. *p = o;
  770. l_setbit(o->gch.marked, FINALIZEDBIT); /* mark it as such */
  771. if (issweepphase(g))
  772. makewhite(g, o); /* "sweep" object */
  773. }
  774. }
  775. /* }====================================================== */
  776. /*
  777. ** {======================================================
  778. ** Local Collection
  779. ** =======================================================
  780. */
  781. /*
  782. ** Traverse a thread, local marking all its collectable objects
  783. */
  784. static void localmarkthread (lua_State *l) {
  785. StkId o = l->stack;
  786. StkId lim = l->stack + l->stacksize; /* real end of stack */
  787. if (o == NULL)
  788. return; /* stack not completely built yet */
  789. for (; o < l->top; o++) { /* mark live elements in the stack */
  790. if (iscollectable(o))
  791. l_setbit(gcvalue(o)->gch.marked, LOCALMARK);
  792. }
  793. for (; o < lim; o++) /* clear not-marked stack slice */
  794. setnilvalue(o);
  795. }
  796. /*
  797. ** Mark all that is locally accessible (accessible directly from
  798. ** a thread)
  799. */
  800. static void localmark (global_State *g) {
  801. GCObject *thread = obj2gco(g->mainthread);
  802. for (; thread != NULL; thread = gch(thread)->next) /* traverse all threads */
  803. localmarkthread(gco2th(thread));
  804. }
  805. static void localsweep (lua_State *L, global_State *g) {
  806. GCObject **p = &g->localgc;
  807. while (*p != NULL) {
  808. GCObject *curr = *p;
  809. if (!islocal(curr)) { /* is 'curr' no more local? */
  810. *p = curr->gch.next; /* remove 'curr' from list */
  811. curr->gch.next = g->allgc; /* link 'curr' in 'allgc' list */
  812. g->allgc = curr;
  813. /* mark it as out of local list */
  814. l_setbit(curr->gch.marked, LOCALMARK);
  815. }
  816. else { /* still local */
  817. if (testbit(curr->gch.marked, LOCALMARK)) { /* locally alive? */
  818. resetbit(curr->gch.marked, LOCALMARK);
  819. p = &curr->gch.next; /* go to next element */
  820. }
  821. else { /* object is dead */
  822. if (curr->gch.tt == LUA_TLCL) { /* is it a Lua closure? */
  823. if (gco2lcl(curr)->p->cache == gco2cl(curr))
  824. gco2lcl(curr)->p->cache = NULL; /* clear cache */
  825. }
  826. *p = curr->gch.next; /* remove 'curr' from list */
  827. freeobj(L, curr); /* erase 'curr' */
  828. }
  829. }
  830. }
  831. }
  832. static void separatelocal (global_State *g, int all) {
  833. GCObject **p = &g->localfin;
  834. GCObject **lastnext = findlast(&g->tobefnz);
  835. while (*p != NULL) {
  836. GCObject *curr = *p;
  837. if (!islocal(curr)) { /* is 'curr' no more local? */
  838. *p = curr->gch.next; /* remove 'curr' from list */
  839. curr->gch.next = g->finobj; /* link 'curr' in 'finobj' list */
  840. g->finobj = curr;
  841. /* mark it as out of local list */
  842. l_setbit(curr->gch.marked, LOCALMARK);
  843. }
  844. else { /* still local */
  845. if (testbit(curr->gch.marked, LOCALMARK) && !all) { /* locally alive? */
  846. resetbit(curr->gch.marked, LOCALMARK);
  847. p = &curr->gch.next; /* go to next element */
  848. }
  849. else { /* object is "dead" */
  850. *p = curr->gch.next; /* remove 'curr' from list */
  851. curr->gch.next = *lastnext; /* link at the end of 'tobefnz' list */
  852. *lastnext = curr;
  853. lastnext = &curr->gch.next;
  854. }
  855. }
  856. }
  857. }
  858. static void luaC_localcollection (lua_State *L) {
  859. global_State *g = G(L);
  860. lua_assert(g->gcstate == GCSpause);
  861. localmark(g);
  862. localsweep(L, g);
  863. separatelocal(g, 0);
  864. callallpendingfinalizers(L, 1);
  865. }
  866. /* }====================================================== */
  867. /*
  868. ** {======================================================
  869. ** GC control
  870. ** =======================================================
  871. */
  872. /*
  873. ** set a reasonable "time" to wait before starting a new GC cycle;
  874. ** cycle will start when memory use hits threshold
  875. */
  876. static void setpause (global_State *g, l_mem estimate) {
  877. l_mem threshold;
  878. estimate = estimate / PAUSEADJ; /* adjust 'estimate' */
  879. threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */
  880. ? estimate * g->gcpause /* no overflow */
  881. : MAX_LMEM; /* overflow; truncate to maximum */
  882. g->GCthreshold = threshold;
  883. luaE_setdebt(g, -g->gclocalpause);
  884. }
  885. /*
  886. ** Enter first sweep phase.
  887. ** The call to 'sweeptolive' makes pointer point to an object inside
  888. ** the list (instead of to the header), so that the real sweep do not
  889. ** need to skip objects created between "now" and the start of the real
  890. ** sweep.
  891. ** Returns how many objects it swept.
  892. */
  893. static int entersweep (lua_State *L) {
  894. global_State *g = G(L);
  895. int n = 0;
  896. g->gcstate = GCSswplocalgc;
  897. lua_assert(g->sweepgc == NULL);
  898. g->sweepgc = sweeptolive(L, &g->localgc, &n);
  899. return n;
  900. }
  901. void luaC_freeallobjects (lua_State *L) {
  902. global_State *g = G(L);
  903. separatetobefnz(g, 1); /* separate all objects with finalizers */
  904. lua_assert(g->finobj == NULL && g->localfin == NULL);
  905. callallpendingfinalizers(L, 0);
  906. lua_assert(g->tobefnz == NULL);
  907. g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */
  908. g->gckind = KGC_NORMAL;
  909. sweepwholelist(L, &g->localgc);
  910. sweepwholelist(L, &g->localfin); /* finalizers can create objs. with fins. */
  911. sweepwholelist(L, &g->finobj);
  912. sweepwholelist(L, &g->allgc);
  913. sweepwholelist(L, &g->mainthread->next);
  914. sweepwholelist(L, &g->fixedgc); /* collect fixed objects */
  915. lua_assert(g->strt.nuse == 0);
  916. }
  917. static l_mem atomic (lua_State *L) {
  918. global_State *g = G(L);
  919. l_mem work = -cast(l_mem, g->GCmemtrav); /* start counting work */
  920. GCObject *origweak, *origall;
  921. lua_assert(!iswhite(obj2gco(g->mainthread)));
  922. markobject(g, L); /* mark running thread */
  923. /* registry and global metatables may be changed by API */
  924. markvalue(g, &g->l_registry);
  925. markmt(g); /* mark basic metatables */
  926. /* remark occasional upvalues of (maybe) dead threads */
  927. remarkupvals(g);
  928. propagateall(g); /* propagate changes */
  929. work += g->GCmemtrav; /* stop counting (do not (re)count grays) */
  930. /* traverse objects caught by write barrier and by 'remarkupvals' */
  931. retraversegrays(g);
  932. work -= g->GCmemtrav; /* restart counting */
  933. convergeephemerons(g);
  934. /* at this point, all strongly accessible objects are marked. */
  935. /* Clear values from weak tables, before checking finalizers */
  936. clearvalues(g, g->weak, NULL);
  937. clearvalues(g, g->allweak, NULL);
  938. origweak = g->weak; origall = g->allweak;
  939. work += g->GCmemtrav; /* stop counting (objects being finalized) */
  940. separatetobefnz(g, 0); /* separate objects to be finalized */
  941. markbeingfnz(g); /* mark objects that will be finalized */
  942. propagateall(g); /* remark, to propagate 'resurrection' */
  943. work -= g->GCmemtrav; /* restart counting */
  944. convergeephemerons(g);
  945. /* at this point, all resurrected objects are marked. */
  946. /* remove dead objects from weak tables */
  947. clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */
  948. clearkeys(g, g->allweak, NULL); /* clear keys from all allweak tables */
  949. /* clear values from resurrected weak tables */
  950. clearvalues(g, g->weak, origweak);
  951. clearvalues(g, g->allweak, origall);
  952. g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
  953. work += g->GCmemtrav; /* complete counting */
  954. return work; /* estimate of memory marked by 'atomic' */
  955. }
  956. static lu_mem sweepstep (lua_State *L, global_State *g,
  957. int nextstate, GCObject **nextlist) {
  958. if (g->sweepgc) {
  959. g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
  960. if (g->sweepgc) /* is there still something to sweep? */
  961. return (GCSWEEPMAX * GCSWEEPCOST);
  962. }
  963. /* else enter next state */
  964. g->gcstate = nextstate;
  965. g->sweepgc = nextlist;
  966. return 0;
  967. }
  968. static lu_mem singlestep (lua_State *L) {
  969. global_State *g = G(L);
  970. switch (g->gcstate) {
  971. case GCSpause: {
  972. /* start to count memory traversed */
  973. g->GCmemtrav = g->strt.size * sizeof(GCObject*);
  974. restartcollection(g);
  975. g->gcstate = GCSpropagate;
  976. return g->GCmemtrav;
  977. }
  978. case GCSpropagate: {
  979. lu_mem oldtrav = g->GCmemtrav;
  980. lua_assert(g->gray);
  981. propagatemark(g);
  982. if (g->gray == NULL) /* no more `gray' objects? */
  983. g->gcstate = GCSatomic; /* finish propagate phase */
  984. return g->GCmemtrav - oldtrav; /* memory traversed in this step */
  985. }
  986. case GCSatomic: {
  987. lu_mem work;
  988. int sw;
  989. propagateall(g); /* make sure gray list is empty */
  990. g->GCestimate = g->GCmemtrav; /* save what was counted */;
  991. work = atomic(L); /* add what was traversed by 'atomic' */
  992. g->GCestimate += work; /* estimate of total memory traversed */
  993. sw = entersweep(L);
  994. return work + sw * GCSWEEPCOST;
  995. }
  996. case GCSswplocalgc: { /* sweep local objects */
  997. return sweepstep(L, g, GCSswpallgc, &g->allgc);
  998. }
  999. case GCSswpallgc: { /* sweep non-local objects */
  1000. return sweepstep(L, g, GCSswpthreads, &g->mainthread->next);
  1001. }
  1002. case GCSswpthreads: { /* sweep threads */
  1003. return sweepstep(L, g, GCSswplocalfin, &g->localfin);
  1004. }
  1005. case GCSswplocalfin: { /* sweep local objects with finalizers */
  1006. return sweepstep(L, g, GCSswpfinobj, &g->finobj);
  1007. }
  1008. case GCSswpfinobj: { /* sweep non-local objects with finalizers */
  1009. return sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
  1010. }
  1011. case GCSswptobefnz: { /* sweep objects to be finalized */
  1012. return sweepstep(L, g, GCSswpend, NULL);
  1013. }
  1014. case GCSswpend: { /* finish sweeps */
  1015. makewhite(g, obj2gco(g->mainthread)); /* sweep main thread */
  1016. checkSizes(L, g);
  1017. g->gcstate = GCSpause; /* finish collection */
  1018. return GCSWEEPCOST;
  1019. }
  1020. default: lua_assert(0); return 0;
  1021. }
  1022. }
  1023. /*
  1024. ** advances the garbage collector until it reaches a state allowed
  1025. ** by 'statemask'
  1026. */
  1027. void luaC_runtilstate (lua_State *L, int statesmask) {
  1028. global_State *g = G(L);
  1029. while (!testbit(statesmask, g->gcstate))
  1030. singlestep(L);
  1031. }
  1032. static void incstep (lua_State *L) {
  1033. global_State *g = G(L);
  1034. l_mem debt = g->GCdebt;
  1035. int stepmul = g->gcstepmul;
  1036. if (stepmul < 40) stepmul = 40; /* avoid ridiculous low values (and 0) */
  1037. /* convert debt from Kb to 'work units' (avoid zero debt and overflows) */
  1038. debt = (debt / STEPMULADJ) + 1;
  1039. debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM;
  1040. do { /* always perform at least one single step */
  1041. lu_mem work = singlestep(L); /* do some work */
  1042. debt -= work;
  1043. } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);
  1044. if (g->gcstate == GCSpause)
  1045. setpause(g, g->GCestimate); /* pause until next cycle */
  1046. else {
  1047. debt = (debt / stepmul) * STEPMULADJ; /* convert 'work units' to Kb */
  1048. luaE_setdebt(g, debt);
  1049. }
  1050. }
  1051. /*
  1052. ** performs a basic GC step
  1053. */
  1054. void luaC_forcestep (lua_State *L) {
  1055. global_State *g = G(L);
  1056. int i;
  1057. incstep(L);
  1058. /* run a few finalizers (or all of them at the end of a collect cycle) */
  1059. for (i = 0; g->tobefnz && (i < GCFINALIZENUM || g->gcstate == GCSpause); i++)
  1060. GCTM(L, 1); /* call one finalizer */
  1061. }
  1062. /*
  1063. ** performs a basic GC step only if collector is running
  1064. */
  1065. void luaC_step (lua_State *L) {
  1066. global_State *g = G(L);
  1067. if (g->gcrunning) {
  1068. if (g->gcstate != GCSpause) {
  1069. luaC_forcestep(L);
  1070. }
  1071. else {
  1072. luaC_localcollection(L);
  1073. if (gettotalbytes(g) > g->GCthreshold) {
  1074. luaC_forcestep(L); /* restart collection */
  1075. }
  1076. else
  1077. luaE_setdebt(g, -g->gclocalpause);
  1078. }
  1079. }
  1080. else luaE_setdebt(g, -GCSTEPSIZE); /* avoid being called too often */
  1081. }
  1082. /*
  1083. ** performs a full GC cycle; if "isemergency", does not call
  1084. ** finalizers (which could change stack positions)
  1085. */
  1086. void luaC_fullgc (lua_State *L, int isemergency) {
  1087. global_State *g = G(L);
  1088. lua_assert(g->gckind == KGC_NORMAL);
  1089. if (isemergency) /* do not run finalizers during emergency GC */
  1090. g->gckind = KGC_EMERGENCY;
  1091. else
  1092. callallpendingfinalizers(L, 1);
  1093. if (keepinvariant(g)) { /* may there be some black objects? */
  1094. /* must sweep all objects to turn them back to white
  1095. (as white has not changed, nothing will be collected) */
  1096. entersweep(L);
  1097. }
  1098. /* finish any pending sweep phase to start a new cycle */
  1099. luaC_runtilstate(L, bitmask(GCSpause));
  1100. luaC_runtilstate(L, ~bitmask(GCSpause)); /* start new collection */
  1101. luaC_runtilstate(L, bitmask(GCSpause)); /* run entire collection */
  1102. g->gckind = KGC_NORMAL;
  1103. setpause(g, gettotalbytes(g));
  1104. if (!isemergency) /* do not run finalizers during emergency GC */
  1105. callallpendingfinalizers(L, 1);
  1106. }
  1107. /* }====================================================== */