lgc.c 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783
  1. /*
  2. ** $Id: lgc.c $
  3. ** Garbage Collector
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lgc_c
  7. #define LUA_CORE
  8. #include "lprefix.h"
  9. #include <string.h>
  10. #include "lua.h"
  11. #include "ldebug.h"
  12. #include "ldo.h"
  13. #include "lfunc.h"
  14. #include "lgc.h"
  15. #include "lmem.h"
  16. #include "lobject.h"
  17. #include "lstate.h"
  18. #include "lstring.h"
  19. #include "ltable.h"
  20. #include "ltm.h"
  21. /*
  22. ** Maximum number of elements to sweep in each single step.
  23. ** (Large enough to dissipate fixed overheads but small enough
  24. ** to allow small steps for the collector.)
  25. */
  26. #define GCSWEEPMAX 20
  27. /*
  28. ** Cost (in work units) of running one finalizer.
  29. */
  30. #define CWUFIN 10
  31. /* mask with all color bits */
  32. #define maskcolors (bitmask(BLACKBIT) | WHITEBITS)
  33. /* mask with all GC bits */
  34. #define maskgcbits (maskcolors | AGEBITS)
  35. /* macro to erase all color bits then set only the current white bit */
  36. #define makewhite(g,x) \
  37. (x->marked = cast_byte((x->marked & ~maskcolors) | luaC_white(g)))
  38. /* make an object gray (neither white nor black) */
  39. #define set2gray(x) resetbits(x->marked, maskcolors)
  40. /* make an object black (coming from any color) */
  41. #define set2black(x) \
  42. (x->marked = cast_byte((x->marked & ~WHITEBITS) | bitmask(BLACKBIT)))
  43. #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
  44. #define keyiswhite(n) (keyiscollectable(n) && iswhite(gckey(n)))
  45. /*
  46. ** Protected access to objects in values
  47. */
  48. #define gcvalueN(o) (iscollectable(o) ? gcvalue(o) : NULL)
  49. /*
  50. ** Access to collectable objects in array part of tables
  51. */
  52. #define gcvalarr(t,i) \
  53. ((*getArrTag(t,i) & BIT_ISCOLLECTABLE) ? getArrVal(t,i)->gc : NULL)
  54. #define markvalue(g,o) { checkliveness(g->mainthread,o); \
  55. if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
  56. #define markkey(g, n) { if keyiswhite(n) reallymarkobject(g,gckey(n)); }
  57. #define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); }
  58. /*
  59. ** mark an object that can be NULL (either because it is really optional,
  60. ** or it was stripped as debug info, or inside an uncompleted structure)
  61. */
  62. #define markobjectN(g,t) { if (t) markobject(g,t); }
  63. static void reallymarkobject (global_State *g, GCObject *o);
  64. static void atomic (lua_State *L);
  65. static void entersweep (lua_State *L);
  66. /*
  67. ** {======================================================
  68. ** Generic functions
  69. ** =======================================================
  70. */
  71. /*
  72. ** one after last element in a hash array
  73. */
  74. #define gnodelast(h) gnode(h, cast_sizet(sizenode(h)))
  75. static l_mem objsize (GCObject *o) {
  76. lu_mem res;
  77. switch (o->tt) {
  78. case LUA_VTABLE: {
  79. res = luaH_size(gco2t(o));
  80. break;
  81. }
  82. case LUA_VLCL: {
  83. LClosure *cl = gco2lcl(o);
  84. res = sizeLclosure(cl->nupvalues);
  85. break;
  86. }
  87. case LUA_VCCL: {
  88. CClosure *cl = gco2ccl(o);
  89. res = sizeCclosure(cl->nupvalues);
  90. break;
  91. break;
  92. }
  93. case LUA_VUSERDATA: {
  94. Udata *u = gco2u(o);
  95. res = sizeudata(u->nuvalue, u->len);
  96. break;
  97. }
  98. case LUA_VPROTO: {
  99. res = luaF_protosize(gco2p(o));
  100. break;
  101. }
  102. case LUA_VTHREAD: {
  103. res = luaE_threadsize(gco2th(o));
  104. break;
  105. }
  106. case LUA_VSHRSTR: {
  107. TString *ts = gco2ts(o);
  108. res = sizestrshr(cast_uint(ts->shrlen));
  109. break;
  110. }
  111. case LUA_VLNGSTR: {
  112. TString *ts = gco2ts(o);
  113. res = luaS_sizelngstr(ts->u.lnglen, ts->shrlen);
  114. break;
  115. }
  116. case LUA_VUPVAL: {
  117. res = sizeof(UpVal);
  118. break;
  119. }
  120. default: res = 0; lua_assert(0);
  121. }
  122. return cast(l_mem, res);
  123. }
  124. static GCObject **getgclist (GCObject *o) {
  125. switch (o->tt) {
  126. case LUA_VTABLE: return &gco2t(o)->gclist;
  127. case LUA_VLCL: return &gco2lcl(o)->gclist;
  128. case LUA_VCCL: return &gco2ccl(o)->gclist;
  129. case LUA_VTHREAD: return &gco2th(o)->gclist;
  130. case LUA_VPROTO: return &gco2p(o)->gclist;
  131. case LUA_VUSERDATA: {
  132. Udata *u = gco2u(o);
  133. lua_assert(u->nuvalue > 0);
  134. return &u->gclist;
  135. }
  136. default: lua_assert(0); return 0;
  137. }
  138. }
  139. /*
  140. ** Link a collectable object 'o' with a known type into the list 'p'.
  141. ** (Must be a macro to access the 'gclist' field in different types.)
  142. */
  143. #define linkgclist(o,p) linkgclist_(obj2gco(o), &(o)->gclist, &(p))
  144. static void linkgclist_ (GCObject *o, GCObject **pnext, GCObject **list) {
  145. lua_assert(!isgray(o)); /* cannot be in a gray list */
  146. *pnext = *list;
  147. *list = o;
  148. set2gray(o); /* now it is */
  149. }
  150. /*
  151. ** Link a generic collectable object 'o' into the list 'p'.
  152. */
  153. #define linkobjgclist(o,p) linkgclist_(obj2gco(o), getgclist(o), &(p))
  154. /*
  155. ** Clear keys for empty entries in tables. If entry is empty, mark its
  156. ** entry as dead. This allows the collection of the key, but keeps its
  157. ** entry in the table: its removal could break a chain and could break
  158. ** a table traversal. Other places never manipulate dead keys, because
  159. ** its associated empty value is enough to signal that the entry is
  160. ** logically empty.
  161. */
  162. static void clearkey (Node *n) {
  163. lua_assert(isempty(gval(n)));
  164. if (keyiscollectable(n))
  165. setdeadkey(n); /* unused key; remove it */
  166. }
  167. /*
  168. ** tells whether a key or value can be cleared from a weak
  169. ** table. Non-collectable objects are never removed from weak
  170. ** tables. Strings behave as 'values', so are never removed too. for
  171. ** other objects: if really collected, cannot keep them; for objects
  172. ** being finalized, keep them in keys, but not in values
  173. */
  174. static int iscleared (global_State *g, const GCObject *o) {
  175. if (o == NULL) return 0; /* non-collectable value */
  176. else if (novariant(o->tt) == LUA_TSTRING) {
  177. markobject(g, o); /* strings are 'values', so are never weak */
  178. return 0;
  179. }
  180. else return iswhite(o);
  181. }
  182. /*
  183. ** Barrier that moves collector forward, that is, marks the white object
  184. ** 'v' being pointed by the black object 'o'. In the generational
  185. ** mode, 'v' must also become old, if 'o' is old; however, it cannot
  186. ** be changed directly to OLD, because it may still point to non-old
  187. ** objects. So, it is marked as OLD0. In the next cycle it will become
  188. ** OLD1, and in the next it will finally become OLD (regular old). By
  189. ** then, any object it points to will also be old. If called in the
  190. ** incremental sweep phase, it clears the black object to white (sweep
  191. ** it) to avoid other barrier calls for this same object. (That cannot
  192. ** be done is generational mode, as its sweep does not distinguish
  193. ** white from dead.)
  194. */
  195. void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
  196. global_State *g = G(L);
  197. lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
  198. if (keepinvariant(g)) { /* must keep invariant? */
  199. reallymarkobject(g, v); /* restore invariant */
  200. if (isold(o)) {
  201. lua_assert(!isold(v)); /* white object could not be old */
  202. setage(v, G_OLD0); /* restore generational invariant */
  203. }
  204. }
  205. else { /* sweep phase */
  206. lua_assert(issweepphase(g));
  207. if (g->gckind != KGC_GENMINOR) /* incremental mode? */
  208. makewhite(g, o); /* mark 'o' as white to avoid other barriers */
  209. }
  210. }
  211. /*
  212. ** barrier that moves collector backward, that is, mark the black object
  213. ** pointing to a white object as gray again.
  214. */
  215. void luaC_barrierback_ (lua_State *L, GCObject *o) {
  216. global_State *g = G(L);
  217. lua_assert(isblack(o) && !isdead(g, o));
  218. lua_assert((g->gckind != KGC_GENMINOR)
  219. || (isold(o) && getage(o) != G_TOUCHED1));
  220. if (getage(o) == G_TOUCHED2) /* already in gray list? */
  221. set2gray(o); /* make it gray to become touched1 */
  222. else /* link it in 'grayagain' and paint it gray */
  223. linkobjgclist(o, g->grayagain);
  224. if (isold(o)) /* generational mode? */
  225. setage(o, G_TOUCHED1); /* touched in current cycle */
  226. }
  227. void luaC_fix (lua_State *L, GCObject *o) {
  228. global_State *g = G(L);
  229. lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */
  230. set2gray(o); /* they will be gray forever */
  231. setage(o, G_OLD); /* and old forever */
  232. g->allgc = o->next; /* remove object from 'allgc' list */
  233. o->next = g->fixedgc; /* link it to 'fixedgc' list */
  234. g->fixedgc = o;
  235. }
  236. /*
  237. ** create a new collectable object (with given type, size, and offset)
  238. ** and link it to 'allgc' list.
  239. */
  240. GCObject *luaC_newobjdt (lua_State *L, lu_byte tt, size_t sz, size_t offset) {
  241. global_State *g = G(L);
  242. char *p = cast_charp(luaM_newobject(L, novariant(tt), sz));
  243. GCObject *o = cast(GCObject *, p + offset);
  244. o->marked = luaC_white(g);
  245. o->tt = tt;
  246. o->next = g->allgc;
  247. g->allgc = o;
  248. return o;
  249. }
  250. /*
  251. ** create a new collectable object with no offset.
  252. */
  253. GCObject *luaC_newobj (lua_State *L, lu_byte tt, size_t sz) {
  254. return luaC_newobjdt(L, tt, sz, 0);
  255. }
  256. /* }====================================================== */
  257. /*
  258. ** {======================================================
  259. ** Mark functions
  260. ** =======================================================
  261. */
  262. /*
  263. ** Mark an object. Userdata with no user values, strings, and closed
  264. ** upvalues are visited and turned black here. Open upvalues are
  265. ** already indirectly linked through their respective threads in the
  266. ** 'twups' list, so they don't go to the gray list; nevertheless, they
  267. ** are kept gray to avoid barriers, as their values will be revisited
  268. ** by the thread or by 'remarkupvals'. Other objects are added to the
  269. ** gray list to be visited (and turned black) later. Both userdata and
  270. ** upvalues can call this function recursively, but this recursion goes
  271. ** for at most two levels: An upvalue cannot refer to another upvalue
  272. ** (only closures can), and a userdata's metatable must be a table.
  273. */
  274. static void reallymarkobject (global_State *g, GCObject *o) {
  275. g->GCmarked += objsize(o);
  276. switch (o->tt) {
  277. case LUA_VSHRSTR:
  278. case LUA_VLNGSTR: {
  279. set2black(o); /* nothing to visit */
  280. break;
  281. }
  282. case LUA_VUPVAL: {
  283. UpVal *uv = gco2upv(o);
  284. if (upisopen(uv))
  285. set2gray(uv); /* open upvalues are kept gray */
  286. else
  287. set2black(uv); /* closed upvalues are visited here */
  288. markvalue(g, uv->v.p); /* mark its content */
  289. break;
  290. }
  291. case LUA_VUSERDATA: {
  292. Udata *u = gco2u(o);
  293. if (u->nuvalue == 0) { /* no user values? */
  294. markobjectN(g, u->metatable); /* mark its metatable */
  295. set2black(u); /* nothing else to mark */
  296. break;
  297. }
  298. /* else... */
  299. } /* FALLTHROUGH */
  300. case LUA_VLCL: case LUA_VCCL: case LUA_VTABLE:
  301. case LUA_VTHREAD: case LUA_VPROTO: {
  302. linkobjgclist(o, g->gray); /* to be visited later */
  303. break;
  304. }
  305. default: lua_assert(0); break;
  306. }
  307. }
  308. /*
  309. ** mark metamethods for basic types
  310. */
  311. static void markmt (global_State *g) {
  312. int i;
  313. for (i=0; i < LUA_NUMTYPES; i++)
  314. markobjectN(g, g->mt[i]);
  315. }
  316. /*
  317. ** mark all objects in list of being-finalized
  318. */
  319. static void markbeingfnz (global_State *g) {
  320. GCObject *o;
  321. for (o = g->tobefnz; o != NULL; o = o->next)
  322. markobject(g, o);
  323. }
  324. /*
  325. ** For each non-marked thread, simulates a barrier between each open
  326. ** upvalue and its value. (If the thread is collected, the value will be
  327. ** assigned to the upvalue, but then it can be too late for the barrier
  328. ** to act. The "barrier" does not need to check colors: A non-marked
  329. ** thread must be young; upvalues cannot be older than their threads; so
  330. ** any visited upvalue must be young too.) Also removes the thread from
  331. ** the list, as it was already visited. Removes also threads with no
  332. ** upvalues, as they have nothing to be checked. (If the thread gets an
  333. ** upvalue later, it will be linked in the list again.)
  334. */
  335. static void remarkupvals (global_State *g) {
  336. lua_State *thread;
  337. lua_State **p = &g->twups;
  338. while ((thread = *p) != NULL) {
  339. if (!iswhite(thread) && thread->openupval != NULL)
  340. p = &thread->twups; /* keep marked thread with upvalues in the list */
  341. else { /* thread is not marked or without upvalues */
  342. UpVal *uv;
  343. lua_assert(!isold(thread) || thread->openupval == NULL);
  344. *p = thread->twups; /* remove thread from the list */
  345. thread->twups = thread; /* mark that it is out of list */
  346. for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {
  347. lua_assert(getage(uv) <= getage(thread));
  348. if (!iswhite(uv)) { /* upvalue already visited? */
  349. lua_assert(upisopen(uv) && isgray(uv));
  350. markvalue(g, uv->v.p); /* mark its value */
  351. }
  352. }
  353. }
  354. }
  355. }
  356. static void cleargraylists (global_State *g) {
  357. g->gray = g->grayagain = NULL;
  358. g->weak = g->allweak = g->ephemeron = NULL;
  359. }
  360. /*
  361. ** mark root set and reset all gray lists, to start a new collection.
  362. ** 'GCmarked' is initialized to count the total number of live bytes
  363. ** during a cycle.
  364. */
  365. static void restartcollection (global_State *g) {
  366. cleargraylists(g);
  367. g->GCmarked = 0;
  368. markobject(g, g->mainthread);
  369. markvalue(g, &g->l_registry);
  370. markmt(g);
  371. markbeingfnz(g); /* mark any finalizing object left from previous cycle */
  372. }
  373. /* }====================================================== */
  374. /*
  375. ** {======================================================
  376. ** Traverse functions
  377. ** =======================================================
  378. */
  379. /*
  380. ** Check whether object 'o' should be kept in the 'grayagain' list for
  381. ** post-processing by 'correctgraylist'. (It could put all old objects
  382. ** in the list and leave all the work to 'correctgraylist', but it is
  383. ** more efficient to avoid adding elements that will be removed.) Only
  384. ** TOUCHED1 objects need to be in the list. TOUCHED2 doesn't need to go
  385. ** back to a gray list, but then it must become OLD. (That is what
  386. ** 'correctgraylist' does when it finds a TOUCHED2 object.)
  387. */
  388. static void genlink (global_State *g, GCObject *o) {
  389. lua_assert(isblack(o));
  390. if (getage(o) == G_TOUCHED1) { /* touched in this cycle? */
  391. linkobjgclist(o, g->grayagain); /* link it back in 'grayagain' */
  392. } /* everything else do not need to be linked back */
  393. else if (getage(o) == G_TOUCHED2)
  394. setage(o, G_OLD); /* advance age */
  395. }
  396. /*
  397. ** Traverse a table with weak values and link it to proper list. During
  398. ** propagate phase, keep it in 'grayagain' list, to be revisited in the
  399. ** atomic phase. In the atomic phase, if table has any white value,
  400. ** put it in 'weak' list, to be cleared.
  401. */
  402. static void traverseweakvalue (global_State *g, Table *h) {
  403. Node *n, *limit = gnodelast(h);
  404. /* if there is array part, assume it may have white values (it is not
  405. worth traversing it now just to check) */
  406. int hasclears = (h->asize > 0);
  407. for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
  408. if (isempty(gval(n))) /* entry is empty? */
  409. clearkey(n); /* clear its key */
  410. else {
  411. lua_assert(!keyisnil(n));
  412. markkey(g, n);
  413. if (!hasclears && iscleared(g, gcvalueN(gval(n)))) /* a white value? */
  414. hasclears = 1; /* table will have to be cleared */
  415. }
  416. }
  417. if (g->gcstate == GCSatomic && hasclears)
  418. linkgclist(h, g->weak); /* has to be cleared later */
  419. else
  420. linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
  421. }
  422. /*
  423. ** Traverse the array part of a table.
  424. */
  425. static int traversearray (global_State *g, Table *h) {
  426. unsigned asize = h->asize;
  427. int marked = 0; /* true if some object is marked in this traversal */
  428. unsigned i;
  429. for (i = 0; i < asize; i++) {
  430. GCObject *o = gcvalarr(h, i);
  431. if (o != NULL && iswhite(o)) {
  432. marked = 1;
  433. reallymarkobject(g, o);
  434. }
  435. }
  436. return marked;
  437. }
  438. /*
  439. ** Traverse an ephemeron table and link it to proper list. Returns true
  440. ** iff any object was marked during this traversal (which implies that
  441. ** convergence has to continue). During propagation phase, keep table
  442. ** in 'grayagain' list, to be visited again in the atomic phase. In
  443. ** the atomic phase, if table has any white->white entry, it has to
  444. ** be revisited during ephemeron convergence (as that key may turn
  445. ** black). Otherwise, if it has any white key, table has to be cleared
  446. ** (in the atomic phase). In generational mode, some tables
  447. ** must be kept in some gray list for post-processing; this is done
  448. ** by 'genlink'.
  449. */
  450. static int traverseephemeron (global_State *g, Table *h, int inv) {
  451. int hasclears = 0; /* true if table has white keys */
  452. int hasww = 0; /* true if table has entry "white-key -> white-value" */
  453. unsigned int i;
  454. unsigned int nsize = sizenode(h);
  455. int marked = traversearray(g, h); /* traverse array part */
  456. /* traverse hash part; if 'inv', traverse descending
  457. (see 'convergeephemerons') */
  458. for (i = 0; i < nsize; i++) {
  459. Node *n = inv ? gnode(h, nsize - 1 - i) : gnode(h, i);
  460. if (isempty(gval(n))) /* entry is empty? */
  461. clearkey(n); /* clear its key */
  462. else if (iscleared(g, gckeyN(n))) { /* key is not marked (yet)? */
  463. hasclears = 1; /* table must be cleared */
  464. if (valiswhite(gval(n))) /* value not marked yet? */
  465. hasww = 1; /* white-white entry */
  466. }
  467. else if (valiswhite(gval(n))) { /* value not marked yet? */
  468. marked = 1;
  469. reallymarkobject(g, gcvalue(gval(n))); /* mark it now */
  470. }
  471. }
  472. /* link table into proper list */
  473. if (g->gcstate == GCSpropagate)
  474. linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
  475. else if (hasww) /* table has white->white entries? */
  476. linkgclist(h, g->ephemeron); /* have to propagate again */
  477. else if (hasclears) /* table has white keys? */
  478. linkgclist(h, g->allweak); /* may have to clean white keys */
  479. else
  480. genlink(g, obj2gco(h)); /* check whether collector still needs to see it */
  481. return marked;
  482. }
  483. static void traversestrongtable (global_State *g, Table *h) {
  484. Node *n, *limit = gnodelast(h);
  485. traversearray(g, h);
  486. for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
  487. if (isempty(gval(n))) /* entry is empty? */
  488. clearkey(n); /* clear its key */
  489. else {
  490. lua_assert(!keyisnil(n));
  491. markkey(g, n);
  492. markvalue(g, gval(n));
  493. }
  494. }
  495. genlink(g, obj2gco(h));
  496. }
  497. static l_mem traversetable (global_State *g, Table *h) {
  498. const char *weakkey, *weakvalue;
  499. const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
  500. TString *smode;
  501. markobjectN(g, h->metatable);
  502. if (mode && ttisshrstring(mode) && /* is there a weak mode? */
  503. (cast_void(smode = tsvalue(mode)),
  504. cast_void(weakkey = strchr(getshrstr(smode), 'k')),
  505. cast_void(weakvalue = strchr(getshrstr(smode), 'v')),
  506. (weakkey || weakvalue))) { /* is really weak? */
  507. if (!weakkey) /* strong keys? */
  508. traverseweakvalue(g, h);
  509. else if (!weakvalue) /* strong values? */
  510. traverseephemeron(g, h, 0);
  511. else /* all weak */
  512. linkgclist(h, g->allweak); /* nothing to traverse now */
  513. }
  514. else /* not weak */
  515. traversestrongtable(g, h);
  516. return 1 + 2*sizenode(h) + h->asize;
  517. }
  518. static l_mem traverseudata (global_State *g, Udata *u) {
  519. int i;
  520. markobjectN(g, u->metatable); /* mark its metatable */
  521. for (i = 0; i < u->nuvalue; i++)
  522. markvalue(g, &u->uv[i].uv);
  523. genlink(g, obj2gco(u));
  524. return 1 + u->nuvalue;
  525. }
  526. /*
  527. ** Traverse a prototype. (While a prototype is being build, its
  528. ** arrays can be larger than needed; the extra slots are filled with
  529. ** NULL, so the use of 'markobjectN')
  530. */
  531. static l_mem traverseproto (global_State *g, Proto *f) {
  532. int i;
  533. markobjectN(g, f->source);
  534. for (i = 0; i < f->sizek; i++) /* mark literals */
  535. markvalue(g, &f->k[i]);
  536. for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
  537. markobjectN(g, f->upvalues[i].name);
  538. for (i = 0; i < f->sizep; i++) /* mark nested protos */
  539. markobjectN(g, f->p[i]);
  540. for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
  541. markobjectN(g, f->locvars[i].varname);
  542. return 1 + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars;
  543. }
  544. static l_mem traverseCclosure (global_State *g, CClosure *cl) {
  545. int i;
  546. for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */
  547. markvalue(g, &cl->upvalue[i]);
  548. return 1 + cl->nupvalues;
  549. }
  550. /*
  551. ** Traverse a Lua closure, marking its prototype and its upvalues.
  552. ** (Both can be NULL while closure is being created.)
  553. */
  554. static l_mem traverseLclosure (global_State *g, LClosure *cl) {
  555. int i;
  556. markobjectN(g, cl->p); /* mark its prototype */
  557. for (i = 0; i < cl->nupvalues; i++) { /* visit its upvalues */
  558. UpVal *uv = cl->upvals[i];
  559. markobjectN(g, uv); /* mark upvalue */
  560. }
  561. return 1 + cl->nupvalues;
  562. }
  563. /*
  564. ** Traverse a thread, marking the elements in the stack up to its top
  565. ** and cleaning the rest of the stack in the final traversal. That
  566. ** ensures that the entire stack have valid (non-dead) objects.
  567. ** Threads have no barriers. In gen. mode, old threads must be visited
  568. ** at every cycle, because they might point to young objects. In inc.
  569. ** mode, the thread can still be modified before the end of the cycle,
  570. ** and therefore it must be visited again in the atomic phase. To ensure
  571. ** these visits, threads must return to a gray list if they are not new
  572. ** (which can only happen in generational mode) or if the traverse is in
  573. ** the propagate phase (which can only happen in incremental mode).
  574. */
  575. static l_mem traversethread (global_State *g, lua_State *th) {
  576. UpVal *uv;
  577. StkId o = th->stack.p;
  578. if (isold(th) || g->gcstate == GCSpropagate)
  579. linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
  580. if (o == NULL)
  581. return 0; /* stack not completely built yet */
  582. lua_assert(g->gcstate == GCSatomic ||
  583. th->openupval == NULL || isintwups(th));
  584. for (; o < th->top.p; o++) /* mark live elements in the stack */
  585. markvalue(g, s2v(o));
  586. for (uv = th->openupval; uv != NULL; uv = uv->u.open.next)
  587. markobject(g, uv); /* open upvalues cannot be collected */
  588. if (g->gcstate == GCSatomic) { /* final traversal? */
  589. if (!g->gcemergency)
  590. luaD_shrinkstack(th); /* do not change stack in emergency cycle */
  591. for (o = th->top.p; o < th->stack_last.p + EXTRA_STACK; o++)
  592. setnilvalue(s2v(o)); /* clear dead stack slice */
  593. /* 'remarkupvals' may have removed thread from 'twups' list */
  594. if (!isintwups(th) && th->openupval != NULL) {
  595. th->twups = g->twups; /* link it back to the list */
  596. g->twups = th;
  597. }
  598. }
  599. return 1 + (th->top.p - th->stack.p);
  600. }
  601. /*
  602. ** traverse one gray object, turning it to black. Return an estimate
  603. ** of the number of slots traversed.
  604. */
  605. static l_mem propagatemark (global_State *g) {
  606. GCObject *o = g->gray;
  607. nw2black(o);
  608. g->gray = *getgclist(o); /* remove from 'gray' list */
  609. switch (o->tt) {
  610. case LUA_VTABLE: return traversetable(g, gco2t(o));
  611. case LUA_VUSERDATA: return traverseudata(g, gco2u(o));
  612. case LUA_VLCL: return traverseLclosure(g, gco2lcl(o));
  613. case LUA_VCCL: return traverseCclosure(g, gco2ccl(o));
  614. case LUA_VPROTO: return traverseproto(g, gco2p(o));
  615. case LUA_VTHREAD: return traversethread(g, gco2th(o));
  616. default: lua_assert(0); return 0;
  617. }
  618. }
  619. static void propagateall (global_State *g) {
  620. while (g->gray)
  621. propagatemark(g);
  622. }
  623. /*
  624. ** Traverse all ephemeron tables propagating marks from keys to values.
  625. ** Repeat until it converges, that is, nothing new is marked. 'dir'
  626. ** inverts the direction of the traversals, trying to speed up
  627. ** convergence on chains in the same table.
  628. */
  629. static void convergeephemerons (global_State *g) {
  630. int changed;
  631. int dir = 0;
  632. do {
  633. GCObject *w;
  634. GCObject *next = g->ephemeron; /* get ephemeron list */
  635. g->ephemeron = NULL; /* tables may return to this list when traversed */
  636. changed = 0;
  637. while ((w = next) != NULL) { /* for each ephemeron table */
  638. Table *h = gco2t(w);
  639. next = h->gclist; /* list is rebuilt during loop */
  640. nw2black(h); /* out of the list (for now) */
  641. if (traverseephemeron(g, h, dir)) { /* marked some value? */
  642. propagateall(g); /* propagate changes */
  643. changed = 1; /* will have to revisit all ephemeron tables */
  644. }
  645. }
  646. dir = !dir; /* invert direction next time */
  647. } while (changed); /* repeat until no more changes */
  648. }
  649. /* }====================================================== */
  650. /*
  651. ** {======================================================
  652. ** Sweep Functions
  653. ** =======================================================
  654. */
  655. /*
  656. ** clear entries with unmarked keys from all weaktables in list 'l'
  657. */
  658. static void clearbykeys (global_State *g, GCObject *l) {
  659. for (; l; l = gco2t(l)->gclist) {
  660. Table *h = gco2t(l);
  661. Node *limit = gnodelast(h);
  662. Node *n;
  663. for (n = gnode(h, 0); n < limit; n++) {
  664. if (iscleared(g, gckeyN(n))) /* unmarked key? */
  665. setempty(gval(n)); /* remove entry */
  666. if (isempty(gval(n))) /* is entry empty? */
  667. clearkey(n); /* clear its key */
  668. }
  669. }
  670. }
  671. /*
  672. ** clear entries with unmarked values from all weaktables in list 'l' up
  673. ** to element 'f'
  674. */
  675. static void clearbyvalues (global_State *g, GCObject *l, GCObject *f) {
  676. for (; l != f; l = gco2t(l)->gclist) {
  677. Table *h = gco2t(l);
  678. Node *n, *limit = gnodelast(h);
  679. unsigned int i;
  680. unsigned int asize = h->asize;
  681. for (i = 0; i < asize; i++) {
  682. GCObject *o = gcvalarr(h, i);
  683. if (iscleared(g, o)) /* value was collected? */
  684. *getArrTag(h, i) = LUA_VEMPTY; /* remove entry */
  685. }
  686. for (n = gnode(h, 0); n < limit; n++) {
  687. if (iscleared(g, gcvalueN(gval(n)))) /* unmarked value? */
  688. setempty(gval(n)); /* remove entry */
  689. if (isempty(gval(n))) /* is entry empty? */
  690. clearkey(n); /* clear its key */
  691. }
  692. }
  693. }
  694. static void freeupval (lua_State *L, UpVal *uv) {
  695. if (upisopen(uv))
  696. luaF_unlinkupval(uv);
  697. luaM_free(L, uv);
  698. }
  699. static void freeobj (lua_State *L, GCObject *o) {
  700. assert_code(l_mem newmem = gettotalbytes(G(L)) - objsize(o));
  701. switch (o->tt) {
  702. case LUA_VPROTO:
  703. luaF_freeproto(L, gco2p(o));
  704. break;
  705. case LUA_VUPVAL:
  706. freeupval(L, gco2upv(o));
  707. break;
  708. case LUA_VLCL: {
  709. LClosure *cl = gco2lcl(o);
  710. luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
  711. break;
  712. }
  713. case LUA_VCCL: {
  714. CClosure *cl = gco2ccl(o);
  715. luaM_freemem(L, cl, sizeCclosure(cl->nupvalues));
  716. break;
  717. }
  718. case LUA_VTABLE:
  719. luaH_free(L, gco2t(o));
  720. break;
  721. case LUA_VTHREAD:
  722. luaE_freethread(L, gco2th(o));
  723. break;
  724. case LUA_VUSERDATA: {
  725. Udata *u = gco2u(o);
  726. luaM_freemem(L, o, sizeudata(u->nuvalue, u->len));
  727. break;
  728. }
  729. case LUA_VSHRSTR: {
  730. TString *ts = gco2ts(o);
  731. luaS_remove(L, ts); /* remove it from hash table */
  732. luaM_freemem(L, ts, sizestrshr(cast_uint(ts->shrlen)));
  733. break;
  734. }
  735. case LUA_VLNGSTR: {
  736. TString *ts = gco2ts(o);
  737. if (ts->shrlen == LSTRMEM) /* must free external string? */
  738. (*ts->falloc)(ts->ud, ts->contents, ts->u.lnglen + 1, 0);
  739. luaM_freemem(L, ts, luaS_sizelngstr(ts->u.lnglen, ts->shrlen));
  740. break;
  741. }
  742. default: lua_assert(0);
  743. }
  744. lua_assert(gettotalbytes(G(L)) == newmem);
  745. }
  746. /*
  747. ** sweep at most 'countin' elements from a list of GCObjects erasing dead
  748. ** objects, where a dead object is one marked with the old (non current)
  749. ** white; change all non-dead objects back to white (and new), preparing
  750. ** for next collection cycle. Return where to continue the traversal or
  751. ** NULL if list is finished.
  752. */
  753. static GCObject **sweeplist (lua_State *L, GCObject **p, l_mem countin) {
  754. global_State *g = G(L);
  755. int ow = otherwhite(g);
  756. int white = luaC_white(g); /* current white */
  757. while (*p != NULL && countin-- > 0) {
  758. GCObject *curr = *p;
  759. int marked = curr->marked;
  760. if (isdeadm(ow, marked)) { /* is 'curr' dead? */
  761. *p = curr->next; /* remove 'curr' from list */
  762. freeobj(L, curr); /* erase 'curr' */
  763. }
  764. else { /* change mark to 'white' and age to 'new' */
  765. curr->marked = cast_byte((marked & ~maskgcbits) | white | G_NEW);
  766. p = &curr->next; /* go to next element */
  767. }
  768. }
  769. return (*p == NULL) ? NULL : p;
  770. }
  771. /*
  772. ** sweep a list until a live object (or end of list)
  773. */
  774. static GCObject **sweeptolive (lua_State *L, GCObject **p) {
  775. GCObject **old = p;
  776. do {
  777. p = sweeplist(L, p, 1);
  778. } while (p == old);
  779. return p;
  780. }
  781. /* }====================================================== */
  782. /*
  783. ** {======================================================
  784. ** Finalization
  785. ** =======================================================
  786. */
  787. /*
  788. ** If possible, shrink string table.
  789. */
  790. static void checkSizes (lua_State *L, global_State *g) {
  791. if (!g->gcemergency) {
  792. if (g->strt.nuse < g->strt.size / 4) /* string table too big? */
  793. luaS_resize(L, g->strt.size / 2);
  794. }
  795. }
  796. /*
  797. ** Get the next udata to be finalized from the 'tobefnz' list, and
  798. ** link it back into the 'allgc' list.
  799. */
  800. static GCObject *udata2finalize (global_State *g) {
  801. GCObject *o = g->tobefnz; /* get first element */
  802. lua_assert(tofinalize(o));
  803. g->tobefnz = o->next; /* remove it from 'tobefnz' list */
  804. o->next = g->allgc; /* return it to 'allgc' list */
  805. g->allgc = o;
  806. resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */
  807. if (issweepphase(g))
  808. makewhite(g, o); /* "sweep" object */
  809. else if (getage(o) == G_OLD1)
  810. g->firstold1 = o; /* it is the first OLD1 object in the list */
  811. return o;
  812. }
  813. static void dothecall (lua_State *L, void *ud) {
  814. UNUSED(ud);
  815. luaD_callnoyield(L, L->top.p - 2, 0);
  816. }
  817. static void GCTM (lua_State *L) {
  818. global_State *g = G(L);
  819. const TValue *tm;
  820. TValue v;
  821. lua_assert(!g->gcemergency);
  822. setgcovalue(L, &v, udata2finalize(g));
  823. tm = luaT_gettmbyobj(L, &v, TM_GC);
  824. if (!notm(tm)) { /* is there a finalizer? */
  825. int status;
  826. lu_byte oldah = L->allowhook;
  827. lu_byte oldgcstp = g->gcstp;
  828. g->gcstp |= GCSTPGC; /* avoid GC steps */
  829. L->allowhook = 0; /* stop debug hooks during GC metamethod */
  830. setobj2s(L, L->top.p++, tm); /* push finalizer... */
  831. setobj2s(L, L->top.p++, &v); /* ... and its argument */
  832. L->ci->callstatus |= CIST_FIN; /* will run a finalizer */
  833. status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top.p - 2), 0);
  834. L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */
  835. L->allowhook = oldah; /* restore hooks */
  836. g->gcstp = oldgcstp; /* restore state */
  837. if (l_unlikely(status != LUA_OK)) { /* error while running __gc? */
  838. luaE_warnerror(L, "__gc");
  839. L->top.p--; /* pops error object */
  840. }
  841. }
  842. }
  843. /*
  844. ** call all pending finalizers
  845. */
  846. static void callallpendingfinalizers (lua_State *L) {
  847. global_State *g = G(L);
  848. while (g->tobefnz)
  849. GCTM(L);
  850. }
  851. /*
  852. ** find last 'next' field in list 'p' list (to add elements in its end)
  853. */
  854. static GCObject **findlast (GCObject **p) {
  855. while (*p != NULL)
  856. p = &(*p)->next;
  857. return p;
  858. }
  859. /*
  860. ** Move all unreachable objects (or 'all' objects) that need
  861. ** finalization from list 'finobj' to list 'tobefnz' (to be finalized).
  862. ** (Note that objects after 'finobjold1' cannot be white, so they
  863. ** don't need to be traversed. In incremental mode, 'finobjold1' is NULL,
  864. ** so the whole list is traversed.)
  865. */
  866. static void separatetobefnz (global_State *g, int all) {
  867. GCObject *curr;
  868. GCObject **p = &g->finobj;
  869. GCObject **lastnext = findlast(&g->tobefnz);
  870. while ((curr = *p) != g->finobjold1) { /* traverse all finalizable objects */
  871. lua_assert(tofinalize(curr));
  872. if (!(iswhite(curr) || all)) /* not being collected? */
  873. p = &curr->next; /* don't bother with it */
  874. else {
  875. if (curr == g->finobjsur) /* removing 'finobjsur'? */
  876. g->finobjsur = curr->next; /* correct it */
  877. *p = curr->next; /* remove 'curr' from 'finobj' list */
  878. curr->next = *lastnext; /* link at the end of 'tobefnz' list */
  879. *lastnext = curr;
  880. lastnext = &curr->next;
  881. }
  882. }
  883. }
  884. /*
  885. ** If pointer 'p' points to 'o', move it to the next element.
  886. */
  887. static void checkpointer (GCObject **p, GCObject *o) {
  888. if (o == *p)
  889. *p = o->next;
  890. }
  891. /*
  892. ** Correct pointers to objects inside 'allgc' list when
  893. ** object 'o' is being removed from the list.
  894. */
  895. static void correctpointers (global_State *g, GCObject *o) {
  896. checkpointer(&g->survival, o);
  897. checkpointer(&g->old1, o);
  898. checkpointer(&g->reallyold, o);
  899. checkpointer(&g->firstold1, o);
  900. }
  901. /*
  902. ** if object 'o' has a finalizer, remove it from 'allgc' list (must
  903. ** search the list to find it) and link it in 'finobj' list.
  904. */
  905. void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
  906. global_State *g = G(L);
  907. if (tofinalize(o) || /* obj. is already marked... */
  908. gfasttm(g, mt, TM_GC) == NULL || /* or has no finalizer... */
  909. (g->gcstp & GCSTPCLS)) /* or closing state? */
  910. return; /* nothing to be done */
  911. else { /* move 'o' to 'finobj' list */
  912. GCObject **p;
  913. if (issweepphase(g)) {
  914. makewhite(g, o); /* "sweep" object 'o' */
  915. if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */
  916. g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */
  917. }
  918. else
  919. correctpointers(g, o);
  920. /* search for pointer pointing to 'o' */
  921. for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
  922. *p = o->next; /* remove 'o' from 'allgc' list */
  923. o->next = g->finobj; /* link it in 'finobj' list */
  924. g->finobj = o;
  925. l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */
  926. }
  927. }
  928. /* }====================================================== */
  929. /*
  930. ** {======================================================
  931. ** Generational Collector
  932. ** =======================================================
  933. */
  934. /*
  935. ** Fields 'GCmarked' and 'GCmajorminor' are used to control the pace and
  936. ** the mode of the collector. They play several roles, depending on the
  937. ** mode of the collector:
  938. ** * KGC_INC:
  939. ** GCmarked: number of marked bytes during a cycle.
  940. ** GCmajorminor: not used.
  941. ** * KGC_GENMINOR
  942. ** GCmarked: number of bytes that became old since last major collection.
  943. ** GCmajorminor: number of bytes marked in last major collection.
  944. ** * KGC_GENMAJOR
  945. ** GCmarked: number of bytes that became old since last major collection.
  946. ** GCmajorminor: number of bytes marked in last major collection.
  947. */
  948. /*
  949. ** Set the "time" to wait before starting a new incremental cycle;
  950. ** cycle will start when number of bytes in use hits the threshold of
  951. ** approximately (marked * pause / 100).
  952. */
  953. static void setpause (global_State *g) {
  954. l_mem threshold = applygcparam(g, PAUSE, g->GCmarked);
  955. l_mem debt = threshold - gettotalbytes(g);
  956. if (debt < 0) debt = 0;
  957. luaE_setdebt(g, debt);
  958. }
  959. /*
  960. ** Sweep a list of objects to enter generational mode. Deletes dead
  961. ** objects and turns the non dead to old. All non-dead threads---which
  962. ** are now old---must be in a gray list. Everything else is not in a
  963. ** gray list. Open upvalues are also kept gray.
  964. */
  965. static void sweep2old (lua_State *L, GCObject **p) {
  966. GCObject *curr;
  967. global_State *g = G(L);
  968. while ((curr = *p) != NULL) {
  969. if (iswhite(curr)) { /* is 'curr' dead? */
  970. lua_assert(isdead(g, curr));
  971. *p = curr->next; /* remove 'curr' from list */
  972. freeobj(L, curr); /* erase 'curr' */
  973. }
  974. else { /* all surviving objects become old */
  975. setage(curr, G_OLD);
  976. if (curr->tt == LUA_VTHREAD) { /* threads must be watched */
  977. lua_State *th = gco2th(curr);
  978. linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
  979. }
  980. else if (curr->tt == LUA_VUPVAL && upisopen(gco2upv(curr)))
  981. set2gray(curr); /* open upvalues are always gray */
  982. else /* everything else is black */
  983. nw2black(curr);
  984. p = &curr->next; /* go to next element */
  985. }
  986. }
  987. }
  988. /*
  989. ** Sweep for generational mode. Delete dead objects. (Because the
  990. ** collection is not incremental, there are no "new white" objects
  991. ** during the sweep. So, any white object must be dead.) For
  992. ** non-dead objects, advance their ages and clear the color of
  993. ** new objects. (Old objects keep their colors.)
  994. ** The ages of G_TOUCHED1 and G_TOUCHED2 objects cannot be advanced
  995. ** here, because these old-generation objects are usually not swept
  996. ** here. They will all be advanced in 'correctgraylist'. That function
  997. ** will also remove objects turned white here from any gray list.
  998. */
  999. static GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p,
  1000. GCObject *limit, GCObject **pfirstold1,
  1001. l_mem *paddedold) {
  1002. static const lu_byte nextage[] = {
  1003. G_SURVIVAL, /* from G_NEW */
  1004. G_OLD1, /* from G_SURVIVAL */
  1005. G_OLD1, /* from G_OLD0 */
  1006. G_OLD, /* from G_OLD1 */
  1007. G_OLD, /* from G_OLD (do not change) */
  1008. G_TOUCHED1, /* from G_TOUCHED1 (do not change) */
  1009. G_TOUCHED2 /* from G_TOUCHED2 (do not change) */
  1010. };
  1011. l_mem addedold = 0;
  1012. int white = luaC_white(g);
  1013. GCObject *curr;
  1014. while ((curr = *p) != limit) {
  1015. if (iswhite(curr)) { /* is 'curr' dead? */
  1016. lua_assert(!isold(curr) && isdead(g, curr));
  1017. *p = curr->next; /* remove 'curr' from list */
  1018. freeobj(L, curr); /* erase 'curr' */
  1019. }
  1020. else { /* correct mark and age */
  1021. int age = getage(curr);
  1022. if (age == G_NEW) { /* new objects go back to white */
  1023. int marked = curr->marked & ~maskgcbits; /* erase GC bits */
  1024. curr->marked = cast_byte(marked | G_SURVIVAL | white);
  1025. }
  1026. else { /* all other objects will be old, and so keep their color */
  1027. lua_assert(age != G_OLD1); /* advanced in 'markold' */
  1028. setage(curr, nextage[age]);
  1029. if (getage(curr) == G_OLD1) {
  1030. addedold += objsize(curr); /* bytes becoming old */
  1031. if (*pfirstold1 == NULL)
  1032. *pfirstold1 = curr; /* first OLD1 object in the list */
  1033. }
  1034. }
  1035. p = &curr->next; /* go to next element */
  1036. }
  1037. }
  1038. *paddedold += addedold;
  1039. return p;
  1040. }
  1041. /*
  1042. ** Correct a list of gray objects. Return a pointer to the last element
  1043. ** left on the list, so that we can link another list to the end of
  1044. ** this one.
  1045. ** Because this correction is done after sweeping, young objects might
  1046. ** be turned white and still be in the list. They are only removed.
  1047. ** 'TOUCHED1' objects are advanced to 'TOUCHED2' and remain on the list;
  1048. ** Non-white threads also remain on the list. 'TOUCHED2' objects and
  1049. ** anything else become regular old, are marked black, and are removed
  1050. ** from the list.
  1051. */
  1052. static GCObject **correctgraylist (GCObject **p) {
  1053. GCObject *curr;
  1054. while ((curr = *p) != NULL) {
  1055. GCObject **next = getgclist(curr);
  1056. if (iswhite(curr))
  1057. goto remove; /* remove all white objects */
  1058. else if (getage(curr) == G_TOUCHED1) { /* touched in this cycle? */
  1059. lua_assert(isgray(curr));
  1060. nw2black(curr); /* make it black, for next barrier */
  1061. setage(curr, G_TOUCHED2);
  1062. goto remain; /* keep it in the list and go to next element */
  1063. }
  1064. else if (curr->tt == LUA_VTHREAD) {
  1065. lua_assert(isgray(curr));
  1066. goto remain; /* keep non-white threads on the list */
  1067. }
  1068. else { /* everything else is removed */
  1069. lua_assert(isold(curr)); /* young objects should be white here */
  1070. if (getage(curr) == G_TOUCHED2) /* advance from TOUCHED2... */
  1071. setage(curr, G_OLD); /* ... to OLD */
  1072. nw2black(curr); /* make object black (to be removed) */
  1073. goto remove;
  1074. }
  1075. remove: *p = *next; continue;
  1076. remain: p = next; continue;
  1077. }
  1078. return p;
  1079. }
  1080. /*
  1081. ** Correct all gray lists, coalescing them into 'grayagain'.
  1082. */
  1083. static void correctgraylists (global_State *g) {
  1084. GCObject **list = correctgraylist(&g->grayagain);
  1085. *list = g->weak; g->weak = NULL;
  1086. list = correctgraylist(list);
  1087. *list = g->allweak; g->allweak = NULL;
  1088. list = correctgraylist(list);
  1089. *list = g->ephemeron; g->ephemeron = NULL;
  1090. correctgraylist(list);
  1091. }
  1092. /*
  1093. ** Mark black 'OLD1' objects when starting a new young collection.
  1094. ** Gray objects are already in some gray list, and so will be visited in
  1095. ** the atomic step.
  1096. */
  1097. static void markold (global_State *g, GCObject *from, GCObject *to) {
  1098. GCObject *p;
  1099. for (p = from; p != to; p = p->next) {
  1100. if (getage(p) == G_OLD1) {
  1101. lua_assert(!iswhite(p));
  1102. setage(p, G_OLD); /* now they are old */
  1103. if (isblack(p))
  1104. reallymarkobject(g, p);
  1105. }
  1106. }
  1107. }
  1108. /*
  1109. ** Finish a young-generation collection.
  1110. */
  1111. static void finishgencycle (lua_State *L, global_State *g) {
  1112. correctgraylists(g);
  1113. checkSizes(L, g);
  1114. g->gcstate = GCSpropagate; /* skip restart */
  1115. if (!g->gcemergency)
  1116. callallpendingfinalizers(L);
  1117. }
  1118. /*
  1119. ** Shifts from a minor collection to major collections. It starts in
  1120. ** the "sweep all" state to clear all objects, which are mostly black
  1121. ** in generational mode.
  1122. */
  1123. static void minor2inc (lua_State *L, global_State *g, lu_byte kind) {
  1124. g->GCmajorminor = g->GCmarked; /* number of live bytes */
  1125. g->gckind = kind;
  1126. g->reallyold = g->old1 = g->survival = NULL;
  1127. g->finobjrold = g->finobjold1 = g->finobjsur = NULL;
  1128. entersweep(L); /* continue as an incremental cycle */
  1129. /* set a debt equal to the step size */
  1130. luaE_setdebt(g, applygcparam(g, STEPSIZE, 100));
  1131. }
  1132. /*
  1133. ** Decide whether to shift to major mode. It shifts if the accumulated
  1134. ** number of added old bytes (counted in 'GCmarked') is larger than
  1135. ** 'minormajor'% of the number of lived bytes after the last major
  1136. ** collection. (This number is kept in 'GCmajorminor'.)
  1137. */
  1138. static int checkminormajor (global_State *g) {
  1139. l_mem limit = applygcparam(g, MINORMAJOR, g->GCmajorminor);
  1140. if (limit == 0)
  1141. return 0; /* special case: 'minormajor' 0 stops major collections */
  1142. return (g->GCmarked >= limit);
  1143. }
  1144. /*
  1145. ** Does a young collection. First, mark 'OLD1' objects. Then does the
  1146. ** atomic step. Then, check whether to continue in minor mode. If so,
  1147. ** sweep all lists and advance pointers. Finally, finish the collection.
  1148. */
  1149. static void youngcollection (lua_State *L, global_State *g) {
  1150. l_mem addedold1 = 0;
  1151. l_mem marked = g->GCmarked; /* preserve 'g->GCmarked' */
  1152. GCObject **psurvival; /* to point to first non-dead survival object */
  1153. GCObject *dummy; /* dummy out parameter to 'sweepgen' */
  1154. lua_assert(g->gcstate == GCSpropagate);
  1155. if (g->firstold1) { /* are there regular OLD1 objects? */
  1156. markold(g, g->firstold1, g->reallyold); /* mark them */
  1157. g->firstold1 = NULL; /* no more OLD1 objects (for now) */
  1158. }
  1159. markold(g, g->finobj, g->finobjrold);
  1160. markold(g, g->tobefnz, NULL);
  1161. atomic(L); /* will lose 'g->marked' */
  1162. /* sweep nursery and get a pointer to its last live element */
  1163. g->gcstate = GCSswpallgc;
  1164. psurvival = sweepgen(L, g, &g->allgc, g->survival, &g->firstold1, &addedold1);
  1165. /* sweep 'survival' */
  1166. sweepgen(L, g, psurvival, g->old1, &g->firstold1, &addedold1);
  1167. g->reallyold = g->old1;
  1168. g->old1 = *psurvival; /* 'survival' survivals are old now */
  1169. g->survival = g->allgc; /* all news are survivals */
  1170. /* repeat for 'finobj' lists */
  1171. dummy = NULL; /* no 'firstold1' optimization for 'finobj' lists */
  1172. psurvival = sweepgen(L, g, &g->finobj, g->finobjsur, &dummy, &addedold1);
  1173. /* sweep 'survival' */
  1174. sweepgen(L, g, psurvival, g->finobjold1, &dummy, &addedold1);
  1175. g->finobjrold = g->finobjold1;
  1176. g->finobjold1 = *psurvival; /* 'survival' survivals are old now */
  1177. g->finobjsur = g->finobj; /* all news are survivals */
  1178. sweepgen(L, g, &g->tobefnz, NULL, &dummy, &addedold1);
  1179. /* keep total number of added old1 bytes */
  1180. g->GCmarked = marked + addedold1;
  1181. /* decide whether to shift to major mode */
  1182. if (checkminormajor(g)) {
  1183. minor2inc(L, g, KGC_GENMAJOR); /* go to major mode */
  1184. g->GCmarked = 0; /* avoid pause in first major cycle (see 'setpause') */
  1185. }
  1186. else
  1187. finishgencycle(L, g); /* still in minor mode; finish it */
  1188. }
  1189. /*
  1190. ** Clears all gray lists, sweeps objects, and prepare sublists to enter
  1191. ** generational mode. The sweeps remove dead objects and turn all
  1192. ** surviving objects to old. Threads go back to 'grayagain'; everything
  1193. ** else is turned black (not in any gray list).
  1194. */
  1195. static void atomic2gen (lua_State *L, global_State *g) {
  1196. cleargraylists(g);
  1197. /* sweep all elements making them old */
  1198. g->gcstate = GCSswpallgc;
  1199. sweep2old(L, &g->allgc);
  1200. /* everything alive now is old */
  1201. g->reallyold = g->old1 = g->survival = g->allgc;
  1202. g->firstold1 = NULL; /* there are no OLD1 objects anywhere */
  1203. /* repeat for 'finobj' lists */
  1204. sweep2old(L, &g->finobj);
  1205. g->finobjrold = g->finobjold1 = g->finobjsur = g->finobj;
  1206. sweep2old(L, &g->tobefnz);
  1207. g->gckind = KGC_GENMINOR;
  1208. g->GCmajorminor = g->GCmarked; /* "base" for number of bytes */
  1209. g->GCmarked = 0; /* to count the number of added old1 bytes */
  1210. finishgencycle(L, g);
  1211. }
  1212. /*
  1213. ** Set debt for the next minor collection, which will happen when
  1214. ** total number of bytes grows 'genminormul'% in relation to
  1215. ** the base, GCmajorminor, which is the number of bytes being used
  1216. ** after the last major collection.
  1217. */
  1218. static void setminordebt (global_State *g) {
  1219. luaE_setdebt(g, applygcparam(g, MINORMUL, g->GCmajorminor));
  1220. }
  1221. /*
  1222. ** Enter generational mode. Must go until the end of an atomic cycle
  1223. ** to ensure that all objects are correctly marked and weak tables
  1224. ** are cleared. Then, turn all objects into old and finishes the
  1225. ** collection.
  1226. */
  1227. static void entergen (lua_State *L, global_State *g) {
  1228. luaC_runtilstate(L, GCSpause, 1); /* prepare to start a new cycle */
  1229. luaC_runtilstate(L, GCSpropagate, 1); /* start new cycle */
  1230. atomic(L); /* propagates all and then do the atomic stuff */
  1231. atomic2gen(L, g);
  1232. setminordebt(g); /* set debt assuming next cycle will be minor */
  1233. }
  1234. /*
  1235. ** Change collector mode to 'newmode'.
  1236. */
  1237. void luaC_changemode (lua_State *L, int newmode) {
  1238. global_State *g = G(L);
  1239. if (g->gckind == KGC_GENMAJOR) /* doing major collections? */
  1240. g->gckind = KGC_INC; /* already incremental but in name */
  1241. if (newmode != g->gckind) { /* does it need to change? */
  1242. if (newmode == KGC_INC) /* entering incremental mode? */
  1243. minor2inc(L, g, KGC_INC); /* entering incremental mode */
  1244. else {
  1245. lua_assert(newmode == KGC_GENMINOR);
  1246. entergen(L, g);
  1247. }
  1248. }
  1249. }
  1250. /*
  1251. ** Does a full collection in generational mode.
  1252. */
  1253. static void fullgen (lua_State *L, global_State *g) {
  1254. minor2inc(L, g, KGC_INC);
  1255. entergen(L, g);
  1256. }
  1257. /*
  1258. ** After an atomic incremental step from a major collection,
  1259. ** check whether collector could return to minor collections.
  1260. ** It checks whether the number of bytes 'tobecollected'
  1261. ** is greater than 'majorminor'% of the number of bytes added
  1262. ** since the last collection ('addedbytes').
  1263. */
  1264. static int checkmajorminor (lua_State *L, global_State *g) {
  1265. if (g->gckind == KGC_GENMAJOR) { /* generational mode? */
  1266. l_mem numbytes = gettotalbytes(g);
  1267. l_mem addedbytes = numbytes - g->GCmajorminor;
  1268. l_mem limit = applygcparam(g, MAJORMINOR, addedbytes);
  1269. l_mem tobecollected = numbytes - g->GCmarked;
  1270. if (tobecollected > limit) {
  1271. atomic2gen(L, g); /* return to generational mode */
  1272. setminordebt(g);
  1273. return 1; /* exit incremental collection */
  1274. }
  1275. }
  1276. g->GCmajorminor = g->GCmarked; /* prepare for next collection */
  1277. return 0; /* stay doing incremental collections */
  1278. }
  1279. /* }====================================================== */
  1280. /*
  1281. ** {======================================================
  1282. ** GC control
  1283. ** =======================================================
  1284. */
  1285. /*
  1286. ** Enter first sweep phase.
  1287. ** The call to 'sweeptolive' makes the pointer point to an object
  1288. ** inside the list (instead of to the header), so that the real sweep do
  1289. ** not need to skip objects created between "now" and the start of the
  1290. ** real sweep.
  1291. */
  1292. static void entersweep (lua_State *L) {
  1293. global_State *g = G(L);
  1294. g->gcstate = GCSswpallgc;
  1295. lua_assert(g->sweepgc == NULL);
  1296. g->sweepgc = sweeptolive(L, &g->allgc);
  1297. }
  1298. /*
  1299. ** Delete all objects in list 'p' until (but not including) object
  1300. ** 'limit'.
  1301. */
  1302. static void deletelist (lua_State *L, GCObject *p, GCObject *limit) {
  1303. while (p != limit) {
  1304. GCObject *next = p->next;
  1305. freeobj(L, p);
  1306. p = next;
  1307. }
  1308. }
  1309. /*
  1310. ** Call all finalizers of the objects in the given Lua state, and
  1311. ** then free all objects, except for the main thread.
  1312. */
  1313. void luaC_freeallobjects (lua_State *L) {
  1314. global_State *g = G(L);
  1315. g->gcstp = GCSTPCLS; /* no extra finalizers after here */
  1316. luaC_changemode(L, KGC_INC);
  1317. separatetobefnz(g, 1); /* separate all objects with finalizers */
  1318. lua_assert(g->finobj == NULL);
  1319. callallpendingfinalizers(L);
  1320. deletelist(L, g->allgc, obj2gco(g->mainthread));
  1321. lua_assert(g->finobj == NULL); /* no new finalizers */
  1322. deletelist(L, g->fixedgc, NULL); /* collect fixed objects */
  1323. lua_assert(g->strt.nuse == 0);
  1324. }
  1325. static void atomic (lua_State *L) {
  1326. global_State *g = G(L);
  1327. GCObject *origweak, *origall;
  1328. GCObject *grayagain = g->grayagain; /* save original list */
  1329. g->grayagain = NULL;
  1330. lua_assert(g->ephemeron == NULL && g->weak == NULL);
  1331. lua_assert(!iswhite(g->mainthread));
  1332. g->gcstate = GCSatomic;
  1333. markobject(g, L); /* mark running thread */
  1334. /* registry and global metatables may be changed by API */
  1335. markvalue(g, &g->l_registry);
  1336. markmt(g); /* mark global metatables */
  1337. propagateall(g); /* empties 'gray' list */
  1338. /* remark occasional upvalues of (maybe) dead threads */
  1339. remarkupvals(g);
  1340. propagateall(g); /* propagate changes */
  1341. g->gray = grayagain;
  1342. propagateall(g); /* traverse 'grayagain' list */
  1343. convergeephemerons(g);
  1344. /* at this point, all strongly accessible objects are marked. */
  1345. /* Clear values from weak tables, before checking finalizers */
  1346. clearbyvalues(g, g->weak, NULL);
  1347. clearbyvalues(g, g->allweak, NULL);
  1348. origweak = g->weak; origall = g->allweak;
  1349. separatetobefnz(g, 0); /* separate objects to be finalized */
  1350. markbeingfnz(g); /* mark objects that will be finalized */
  1351. propagateall(g); /* remark, to propagate 'resurrection' */
  1352. convergeephemerons(g);
  1353. /* at this point, all resurrected objects are marked. */
  1354. /* remove dead objects from weak tables */
  1355. clearbykeys(g, g->ephemeron); /* clear keys from all ephemeron */
  1356. clearbykeys(g, g->allweak); /* clear keys from all 'allweak' */
  1357. /* clear values from resurrected weak tables */
  1358. clearbyvalues(g, g->weak, origweak);
  1359. clearbyvalues(g, g->allweak, origall);
  1360. luaS_clearcache(g);
  1361. g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
  1362. lua_assert(g->gray == NULL);
  1363. }
  1364. /*
  1365. ** Do a sweep step. The normal case (not fast) sweeps at most GCSWEEPMAX
  1366. ** elements. The fast case sweeps the whole list.
  1367. */
  1368. static void sweepstep (lua_State *L, global_State *g,
  1369. lu_byte nextstate, GCObject **nextlist, int fast) {
  1370. if (g->sweepgc)
  1371. g->sweepgc = sweeplist(L, g->sweepgc, fast ? MAX_LMEM : GCSWEEPMAX);
  1372. else { /* enter next state */
  1373. g->gcstate = nextstate;
  1374. g->sweepgc = nextlist;
  1375. }
  1376. }
  1377. /*
  1378. ** Performs one incremental "step" in an incremental garbage collection.
  1379. ** For indivisible work, a step goes to the next state. When marking
  1380. ** (propagating), a step traverses one object. When sweeping, a step
  1381. ** sweeps GCSWEEPMAX objects, to avoid a big overhead for sweeping
  1382. ** objects one by one. (Sweeping is inexpensive, no matter the
  1383. ** object.) When 'fast' is true, 'singlestep' tries to finish a state
  1384. ** "as fast as possible". In particular, it skips the propagation
  1385. ** phase and leaves all objects to be traversed by the atomic phase:
  1386. ** That avoids traversing twice some objects, such as threads and
  1387. ** weak tables.
  1388. */
  1389. #define step2pause -3 /* finished collection; entered pause state */
  1390. #define atomicstep -2 /* atomic step */
  1391. #define step2minor -1 /* moved to minor collections */
  1392. static l_mem singlestep (lua_State *L, int fast) {
  1393. global_State *g = G(L);
  1394. l_mem stepresult;
  1395. lua_assert(!g->gcstopem); /* collector is not reentrant */
  1396. g->gcstopem = 1; /* no emergency collections while collecting */
  1397. switch (g->gcstate) {
  1398. case GCSpause: {
  1399. restartcollection(g);
  1400. g->gcstate = GCSpropagate;
  1401. stepresult = 1;
  1402. break;
  1403. }
  1404. case GCSpropagate: {
  1405. if (fast || g->gray == NULL) {
  1406. g->gcstate = GCSenteratomic; /* finish propagate phase */
  1407. stepresult = 1;
  1408. }
  1409. else
  1410. stepresult = propagatemark(g); /* traverse one gray object */
  1411. break;
  1412. }
  1413. case GCSenteratomic: {
  1414. atomic(L);
  1415. if (checkmajorminor(L, g))
  1416. stepresult = step2minor;
  1417. else {
  1418. entersweep(L);
  1419. stepresult = atomicstep;
  1420. }
  1421. break;
  1422. }
  1423. case GCSswpallgc: { /* sweep "regular" objects */
  1424. sweepstep(L, g, GCSswpfinobj, &g->finobj, fast);
  1425. stepresult = GCSWEEPMAX;
  1426. break;
  1427. }
  1428. case GCSswpfinobj: { /* sweep objects with finalizers */
  1429. sweepstep(L, g, GCSswptobefnz, &g->tobefnz, fast);
  1430. stepresult = GCSWEEPMAX;
  1431. break;
  1432. }
  1433. case GCSswptobefnz: { /* sweep objects to be finalized */
  1434. sweepstep(L, g, GCSswpend, NULL, fast);
  1435. stepresult = GCSWEEPMAX;
  1436. break;
  1437. }
  1438. case GCSswpend: { /* finish sweeps */
  1439. checkSizes(L, g);
  1440. g->gcstate = GCScallfin;
  1441. stepresult = GCSWEEPMAX;
  1442. break;
  1443. }
  1444. case GCScallfin: { /* call finalizers */
  1445. if (g->tobefnz && !g->gcemergency) {
  1446. g->gcstopem = 0; /* ok collections during finalizers */
  1447. GCTM(L); /* call one finalizer */
  1448. stepresult = CWUFIN;
  1449. }
  1450. else { /* emergency mode or no more finalizers */
  1451. g->gcstate = GCSpause; /* finish collection */
  1452. stepresult = step2pause;
  1453. }
  1454. break;
  1455. }
  1456. default: lua_assert(0); return 0;
  1457. }
  1458. g->gcstopem = 0;
  1459. return stepresult;
  1460. }
  1461. /*
  1462. ** Advances the garbage collector until it reaches the given state.
  1463. ** (The option 'fast' is only for testing; in normal code, 'fast'
  1464. ** here is always true.)
  1465. */
  1466. void luaC_runtilstate (lua_State *L, int state, int fast) {
  1467. global_State *g = G(L);
  1468. lua_assert(g->gckind == KGC_INC);
  1469. while (state != g->gcstate)
  1470. singlestep(L, fast);
  1471. }
  1472. /*
  1473. ** Performs a basic incremental step. The step size is
  1474. ** converted from bytes to "units of work"; then the function loops
  1475. ** running single steps until adding that many units of work or
  1476. ** finishing a cycle (pause state). Finally, it sets the debt that
  1477. ** controls when next step will be performed.
  1478. */
  1479. static void incstep (lua_State *L, global_State *g) {
  1480. l_mem stepsize = applygcparam(g, STEPSIZE, 100);
  1481. l_mem work2do = applygcparam(g, STEPMUL, stepsize / cast_int(sizeof(void*)));
  1482. l_mem stres;
  1483. int fast = (work2do == 0); /* special case: do a full collection */
  1484. do { /* repeat until enough work */
  1485. stres = singlestep(L, fast); /* perform one single step */
  1486. if (stres == step2minor) /* returned to minor collections? */
  1487. return; /* nothing else to be done here */
  1488. else if (stres == step2pause || (stres == atomicstep && !fast))
  1489. break; /* end of cycle or atomic */
  1490. else
  1491. work2do -= stres;
  1492. } while (fast || work2do > 0);
  1493. if (g->gcstate == GCSpause)
  1494. setpause(g); /* pause until next cycle */
  1495. else
  1496. luaE_setdebt(g, stepsize);
  1497. }
  1498. #if !defined(luai_tracegc)
  1499. #define luai_tracegc(L,f) ((void)0)
  1500. #endif
  1501. /*
  1502. ** Performs a basic GC step if collector is running. (If collector was
  1503. ** stopped by the user, set a reasonable debt to avoid it being called
  1504. ** at every single check.)
  1505. */
  1506. void luaC_step (lua_State *L) {
  1507. global_State *g = G(L);
  1508. lua_assert(!g->gcemergency);
  1509. if (!gcrunning(g)) { /* not running? */
  1510. if (g->gcstp & GCSTPUSR) /* stopped by the user? */
  1511. luaE_setdebt(g, 20000);
  1512. }
  1513. else {
  1514. luai_tracegc(L, 1); /* for internal debugging */
  1515. switch (g->gckind) {
  1516. case KGC_INC: case KGC_GENMAJOR:
  1517. incstep(L, g);
  1518. break;
  1519. case KGC_GENMINOR:
  1520. youngcollection(L, g);
  1521. setminordebt(g);
  1522. break;
  1523. }
  1524. luai_tracegc(L, 0); /* for internal debugging */
  1525. }
  1526. }
  1527. /*
  1528. ** Perform a full collection in incremental mode.
  1529. ** Before running the collection, check 'keepinvariant'; if it is true,
  1530. ** there may be some objects marked as black, so the collector has
  1531. ** to sweep all objects to turn them back to white (as white has not
  1532. ** changed, nothing will be collected).
  1533. */
  1534. static void fullinc (lua_State *L, global_State *g) {
  1535. if (keepinvariant(g)) /* black objects? */
  1536. entersweep(L); /* sweep everything to turn them back to white */
  1537. /* finish any pending sweep phase to start a new cycle */
  1538. luaC_runtilstate(L, GCSpause, 1);
  1539. luaC_runtilstate(L, GCScallfin, 1); /* run up to finalizers */
  1540. luaC_runtilstate(L, GCSpause, 1); /* finish collection */
  1541. setpause(g);
  1542. }
  1543. /*
  1544. ** Performs a full GC cycle; if 'isemergency', set a flag to avoid
  1545. ** some operations which could change the interpreter state in some
  1546. ** unexpected ways (running finalizers and shrinking some structures).
  1547. */
  1548. void luaC_fullgc (lua_State *L, int isemergency) {
  1549. global_State *g = G(L);
  1550. lua_assert(!g->gcemergency);
  1551. g->gcemergency = cast_byte(isemergency); /* set flag */
  1552. switch (g->gckind) {
  1553. case KGC_GENMINOR: fullgen(L, g); break;
  1554. case KGC_INC: fullinc(L, g); break;
  1555. case KGC_GENMAJOR:
  1556. g->gckind = KGC_INC;
  1557. fullinc(L, g);
  1558. g->gckind = KGC_GENMAJOR;
  1559. break;
  1560. }
  1561. g->gcemergency = 0;
  1562. }
  1563. /* }====================================================== */