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