lgc.c 56 KB

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