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