lgc.c 53 KB

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