xref: /minix/external/mit/lua/dist/src/lgc.c (revision 0a6a1f1d)
1 /*	$NetBSD: lgc.c,v 1.4 2015/10/08 13:21:00 mbalmer Exp $	*/
2 
3 /*
4 ** Id: lgc.c,v 2.205 2015/03/25 13:42:19 roberto Exp
5 ** Garbage Collector
6 ** See Copyright Notice in lua.h
7 */
8 
9 #define lgc_c
10 #define LUA_CORE
11 
12 #include "lprefix.h"
13 
14 
15 #ifndef _KERNEL
16 #include <string.h>
17 #endif
18 
19 #include "lua.h"
20 
21 #include "ldebug.h"
22 #include "ldo.h"
23 #include "lfunc.h"
24 #include "lgc.h"
25 #include "lmem.h"
26 #include "lobject.h"
27 #include "lstate.h"
28 #include "lstring.h"
29 #include "ltable.h"
30 #include "ltm.h"
31 
32 
33 /*
34 ** internal state for collector while inside the atomic phase. The
35 ** collector should never be in this state while running regular code.
36 */
37 #define GCSinsideatomic		(GCSpause + 1)
38 
39 /*
40 ** cost of sweeping one element (the size of a small object divided
41 ** by some adjust for the sweep speed)
42 */
43 #define GCSWEEPCOST	((sizeof(TString) + 4) / 4)
44 
45 /* maximum number of elements to sweep in each single step */
46 #define GCSWEEPMAX	(cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4))
47 
48 /* cost of calling one finalizer */
49 #define GCFINALIZECOST	GCSWEEPCOST
50 
51 
52 /*
53 ** macro to adjust 'stepmul': 'stepmul' is actually used like
54 ** 'stepmul / STEPMULADJ' (value chosen by tests)
55 */
56 #define STEPMULADJ		200
57 
58 
59 /*
60 ** macro to adjust 'pause': 'pause' is actually used like
61 ** 'pause / PAUSEADJ' (value chosen by tests)
62 */
63 #define PAUSEADJ		100
64 
65 
66 /*
67 ** 'makewhite' erases all color bits then sets only the current white
68 ** bit
69 */
70 #define maskcolors	(~(bitmask(BLACKBIT) | WHITEBITS))
71 #define makewhite(g,x)	\
72  (x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g)))
73 
74 #define white2gray(x)	resetbits(x->marked, WHITEBITS)
75 #define black2gray(x)	resetbit(x->marked, BLACKBIT)
76 
77 
78 #define valiswhite(x)   (iscollectable(x) && iswhite(gcvalue(x)))
79 
80 #define checkdeadkey(n)	lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))
81 
82 
83 #define checkconsistency(obj)  \
84   lua_longassert(!iscollectable(obj) || righttt(obj))
85 
86 
87 #define markvalue(g,o) { checkconsistency(o); \
88   if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
89 
90 #define markobject(g,t)	{ if (iswhite(t)) reallymarkobject(g, obj2gco(t)); }
91 
92 /*
93 ** mark an object that can be NULL (either because it is really optional,
94 ** or it was stripped as debug info, or inside an uncompleted structure)
95 */
96 #define markobjectN(g,t)	{ if (t) markobject(g,t); }
97 
98 static void reallymarkobject (global_State *g, GCObject *o);
99 
100 
101 /*
102 ** {======================================================
103 ** Generic functions
104 ** =======================================================
105 */
106 
107 
108 /*
109 ** one after last element in a hash array
110 */
111 #define gnodelast(h)	gnode(h, cast(size_t, sizenode(h)))
112 
113 
114 /*
115 ** link collectable object 'o' into list pointed by 'p'
116 */
117 #define linkgclist(o,p)	((o)->gclist = (p), (p) = obj2gco(o))
118 
119 
120 /*
121 ** if key is not marked, mark its entry as dead (therefore removing it
122 ** from the table)
123 */
removeentry(Node * n)124 static void removeentry (Node *n) {
125   lua_assert(ttisnil(gval(n)));
126   if (valiswhite(gkey(n)))
127     setdeadvalue(wgkey(n));  /* unused and unmarked key; remove it */
128 }
129 
130 
131 /*
132 ** tells whether a key or value can be cleared from a weak
133 ** table. Non-collectable objects are never removed from weak
134 ** tables. Strings behave as 'values', so are never removed too. for
135 ** other objects: if really collected, cannot keep them; for objects
136 ** being finalized, keep them in keys, but not in values
137 */
iscleared(global_State * g,const TValue * o)138 static int iscleared (global_State *g, const TValue *o) {
139   if (!iscollectable(o)) return 0;
140   else if (ttisstring(o)) {
141     markobject(g, tsvalue(o));  /* strings are 'values', so are never weak */
142     return 0;
143   }
144   else return iswhite(gcvalue(o));
145 }
146 
147 
148 /*
149 ** barrier that moves collector forward, that is, mark the white object
150 ** being pointed by a black object. (If in sweep phase, clear the black
151 ** object to white [sweep it] to avoid other barrier calls for this
152 ** same object.)
153 */
luaC_barrier_(lua_State * L,GCObject * o,GCObject * v)154 void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
155   global_State *g = G(L);
156   lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
157   if (keepinvariant(g))  /* must keep invariant? */
158     reallymarkobject(g, v);  /* restore invariant */
159   else {  /* sweep phase */
160     lua_assert(issweepphase(g));
161     makewhite(g, o);  /* mark main obj. as white to avoid other barriers */
162   }
163 }
164 
165 
166 /*
167 ** barrier that moves collector backward, that is, mark the black object
168 ** pointing to a white object as gray again.
169 */
luaC_barrierback_(lua_State * L,Table * t)170 void luaC_barrierback_ (lua_State *L, Table *t) {
171   global_State *g = G(L);
172   lua_assert(isblack(t) && !isdead(g, t));
173   black2gray(t);  /* make table gray (again) */
174   linkgclist(t, g->grayagain);
175 }
176 
177 
178 /*
179 ** barrier for assignments to closed upvalues. Because upvalues are
180 ** shared among closures, it is impossible to know the color of all
181 ** closures pointing to it. So, we assume that the object being assigned
182 ** must be marked.
183 */
luaC_upvalbarrier_(lua_State * L,UpVal * uv)184 void luaC_upvalbarrier_ (lua_State *L, UpVal *uv) {
185   global_State *g = G(L);
186   GCObject *o = gcvalue(uv->v);
187   lua_assert(!upisopen(uv));  /* ensured by macro luaC_upvalbarrier */
188   if (keepinvariant(g))
189     markobject(g, o);
190 }
191 
192 
luaC_fix(lua_State * L,GCObject * o)193 void luaC_fix (lua_State *L, GCObject *o) {
194   global_State *g = G(L);
195   lua_assert(g->allgc == o);  /* object must be 1st in 'allgc' list! */
196   white2gray(o);  /* they will be gray forever */
197   g->allgc = o->next;  /* remove object from 'allgc' list */
198   o->next = g->fixedgc;  /* link it to 'fixedgc' list */
199   g->fixedgc = o;
200 }
201 
202 
203 /*
204 ** create a new collectable object (with given type and size) and link
205 ** it to 'allgc' list.
206 */
luaC_newobj(lua_State * L,int tt,size_t sz)207 GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
208   global_State *g = G(L);
209   GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz));
210   o->marked = luaC_white(g);
211   o->tt = tt;
212   o->next = g->allgc;
213   g->allgc = o;
214   return o;
215 }
216 
217 /* }====================================================== */
218 
219 
220 
221 /*
222 ** {======================================================
223 ** Mark functions
224 ** =======================================================
225 */
226 
227 
228 /*
229 ** mark an object. Userdata, strings, and closed upvalues are visited
230 ** and turned black here. Other objects are marked gray and added
231 ** to appropriate list to be visited (and turned black) later. (Open
232 ** upvalues are already linked in 'headuv' list.)
233 */
reallymarkobject(global_State * g,GCObject * o)234 static void reallymarkobject (global_State *g, GCObject *o) {
235  reentry:
236   white2gray(o);
237   switch (o->tt) {
238     case LUA_TSHRSTR: {
239       gray2black(o);
240       g->GCmemtrav += sizelstring(gco2ts(o)->shrlen);
241       break;
242     }
243     case LUA_TLNGSTR: {
244       gray2black(o);
245       g->GCmemtrav += sizelstring(gco2ts(o)->u.lnglen);
246       break;
247     }
248     case LUA_TUSERDATA: {
249       TValue uvalue;
250       markobjectN(g, gco2u(o)->metatable);  /* mark its metatable */
251       gray2black(o);
252       g->GCmemtrav += sizeudata(gco2u(o));
253       getuservalue(g->mainthread, gco2u(o), &uvalue);
254       if (valiswhite(&uvalue)) {  /* markvalue(g, &uvalue); */
255         o = gcvalue(&uvalue);
256         goto reentry;
257       }
258       break;
259     }
260     case LUA_TLCL: {
261       linkgclist(gco2lcl(o), g->gray);
262       break;
263     }
264     case LUA_TCCL: {
265       linkgclist(gco2ccl(o), g->gray);
266       break;
267     }
268     case LUA_TTABLE: {
269       linkgclist(gco2t(o), g->gray);
270       break;
271     }
272     case LUA_TTHREAD: {
273       linkgclist(gco2th(o), g->gray);
274       break;
275     }
276     case LUA_TPROTO: {
277       linkgclist(gco2p(o), g->gray);
278       break;
279     }
280     default: lua_assert(0); break;
281   }
282 }
283 
284 
285 /*
286 ** mark metamethods for basic types
287 */
markmt(global_State * g)288 static void markmt (global_State *g) {
289   int i;
290   for (i=0; i < LUA_NUMTAGS; i++)
291     markobjectN(g, g->mt[i]);
292 }
293 
294 
295 /*
296 ** mark all objects in list of being-finalized
297 */
markbeingfnz(global_State * g)298 static void markbeingfnz (global_State *g) {
299   GCObject *o;
300   for (o = g->tobefnz; o != NULL; o = o->next)
301     markobject(g, o);
302 }
303 
304 
305 /*
306 ** Mark all values stored in marked open upvalues from non-marked threads.
307 ** (Values from marked threads were already marked when traversing the
308 ** thread.) Remove from the list threads that no longer have upvalues and
309 ** not-marked threads.
310 */
remarkupvals(global_State * g)311 static void remarkupvals (global_State *g) {
312   lua_State *thread;
313   lua_State **p = &g->twups;
314   while ((thread = *p) != NULL) {
315     lua_assert(!isblack(thread));  /* threads are never black */
316     if (isgray(thread) && thread->openupval != NULL)
317       p = &thread->twups;  /* keep marked thread with upvalues in the list */
318     else {  /* thread is not marked or without upvalues */
319       UpVal *uv;
320       *p = thread->twups;  /* remove thread from the list */
321       thread->twups = thread;  /* mark that it is out of list */
322       for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {
323         if (uv->u.open.touched) {
324           markvalue(g, uv->v);  /* remark upvalue's value */
325           uv->u.open.touched = 0;
326         }
327       }
328     }
329   }
330 }
331 
332 
333 /*
334 ** mark root set and reset all gray lists, to start a new collection
335 */
restartcollection(global_State * g)336 static void restartcollection (global_State *g) {
337   g->gray = g->grayagain = NULL;
338   g->weak = g->allweak = g->ephemeron = NULL;
339   markobject(g, g->mainthread);
340   markvalue(g, &g->l_registry);
341   markmt(g);
342   markbeingfnz(g);  /* mark any finalizing object left from previous cycle */
343 }
344 
345 /* }====================================================== */
346 
347 
348 /*
349 ** {======================================================
350 ** Traverse functions
351 ** =======================================================
352 */
353 
354 /*
355 ** Traverse a table with weak values and link it to proper list. During
356 ** propagate phase, keep it in 'grayagain' list, to be revisited in the
357 ** atomic phase. In the atomic phase, if table has any white value,
358 ** put it in 'weak' list, to be cleared.
359 */
traverseweakvalue(global_State * g,Table * h)360 static void traverseweakvalue (global_State *g, Table *h) {
361   Node *n, *limit = gnodelast(h);
362   /* if there is array part, assume it may have white values (it is not
363      worth traversing it now just to check) */
364   int hasclears = (h->sizearray > 0);
365   for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */
366     checkdeadkey(n);
367     if (ttisnil(gval(n)))  /* entry is empty? */
368       removeentry(n);  /* remove it */
369     else {
370       lua_assert(!ttisnil(gkey(n)));
371       markvalue(g, gkey(n));  /* mark key */
372       if (!hasclears && iscleared(g, gval(n)))  /* is there a white value? */
373         hasclears = 1;  /* table will have to be cleared */
374     }
375   }
376   if (g->gcstate == GCSpropagate)
377     linkgclist(h, g->grayagain);  /* must retraverse it in atomic phase */
378   else if (hasclears)
379     linkgclist(h, g->weak);  /* has to be cleared later */
380 }
381 
382 
383 /*
384 ** Traverse an ephemeron table and link it to proper list. Returns true
385 ** iff any object was marked during this traversal (which implies that
386 ** convergence has to continue). During propagation phase, keep table
387 ** in 'grayagain' list, to be visited again in the atomic phase. In
388 ** the atomic phase, if table has any white->white entry, it has to
389 ** be revisited during ephemeron convergence (as that key may turn
390 ** black). Otherwise, if it has any white key, table has to be cleared
391 ** (in the atomic phase).
392 */
traverseephemeron(global_State * g,Table * h)393 static int traverseephemeron (global_State *g, Table *h) {
394   int marked = 0;  /* true if an object is marked in this traversal */
395   int hasclears = 0;  /* true if table has white keys */
396   int hasww = 0;  /* true if table has entry "white-key -> white-value" */
397   Node *n, *limit = gnodelast(h);
398   unsigned int i;
399   /* traverse array part */
400   for (i = 0; i < h->sizearray; i++) {
401     if (valiswhite(&h->array[i])) {
402       marked = 1;
403       reallymarkobject(g, gcvalue(&h->array[i]));
404     }
405   }
406   /* traverse hash part */
407   for (n = gnode(h, 0); n < limit; n++) {
408     checkdeadkey(n);
409     if (ttisnil(gval(n)))  /* entry is empty? */
410       removeentry(n);  /* remove it */
411     else if (iscleared(g, gkey(n))) {  /* key is not marked (yet)? */
412       hasclears = 1;  /* table must be cleared */
413       if (valiswhite(gval(n)))  /* value not marked yet? */
414         hasww = 1;  /* white-white entry */
415     }
416     else if (valiswhite(gval(n))) {  /* value not marked yet? */
417       marked = 1;
418       reallymarkobject(g, gcvalue(gval(n)));  /* mark it now */
419     }
420   }
421   /* link table into proper list */
422   if (g->gcstate == GCSpropagate)
423     linkgclist(h, g->grayagain);  /* must retraverse it in atomic phase */
424   else if (hasww)  /* table has white->white entries? */
425     linkgclist(h, g->ephemeron);  /* have to propagate again */
426   else if (hasclears)  /* table has white keys? */
427     linkgclist(h, g->allweak);  /* may have to clean white keys */
428   return marked;
429 }
430 
431 
traversestrongtable(global_State * g,Table * h)432 static void traversestrongtable (global_State *g, Table *h) {
433   Node *n, *limit = gnodelast(h);
434   unsigned int i;
435   for (i = 0; i < h->sizearray; i++)  /* traverse array part */
436     markvalue(g, &h->array[i]);
437   for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */
438     checkdeadkey(n);
439     if (ttisnil(gval(n)))  /* entry is empty? */
440       removeentry(n);  /* remove it */
441     else {
442       lua_assert(!ttisnil(gkey(n)));
443       markvalue(g, gkey(n));  /* mark key */
444       markvalue(g, gval(n));  /* mark value */
445     }
446   }
447 }
448 
449 
traversetable(global_State * g,Table * h)450 static lu_mem traversetable (global_State *g, Table *h) {
451   const char *weakkey, *weakvalue;
452   const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
453   markobjectN(g, h->metatable);
454   if (mode && ttisstring(mode) &&  /* is there a weak mode? */
455       ((weakkey = strchr(svalue(mode), 'k')),
456        (weakvalue = strchr(svalue(mode), 'v')),
457        (weakkey || weakvalue))) {  /* is really weak? */
458     black2gray(h);  /* keep table gray */
459     if (!weakkey)  /* strong keys? */
460       traverseweakvalue(g, h);
461     else if (!weakvalue)  /* strong values? */
462       traverseephemeron(g, h);
463     else  /* all weak */
464       linkgclist(h, g->allweak);  /* nothing to traverse now */
465   }
466   else  /* not weak */
467     traversestrongtable(g, h);
468   return sizeof(Table) + sizeof(TValue) * h->sizearray +
469                          sizeof(Node) * cast(size_t, sizenode(h));
470 }
471 
472 
473 /*
474 ** Traverse a prototype. (While a prototype is being build, its
475 ** arrays can be larger than needed; the extra slots are filled with
476 ** NULL, so the use of 'markobjectN')
477 */
traverseproto(global_State * g,Proto * f)478 static int traverseproto (global_State *g, Proto *f) {
479   int i;
480   if (f->cache && iswhite(f->cache))
481     f->cache = NULL;  /* allow cache to be collected */
482   markobjectN(g, f->source);
483   for (i = 0; i < f->sizek; i++)  /* mark literals */
484     markvalue(g, &f->k[i]);
485   for (i = 0; i < f->sizeupvalues; i++)  /* mark upvalue names */
486     markobjectN(g, f->upvalues[i].name);
487   for (i = 0; i < f->sizep; i++)  /* mark nested protos */
488     markobjectN(g, f->p[i]);
489   for (i = 0; i < f->sizelocvars; i++)  /* mark local-variable names */
490     markobjectN(g, f->locvars[i].varname);
491   return sizeof(Proto) + sizeof(Instruction) * f->sizecode +
492                          sizeof(Proto *) * f->sizep +
493                          sizeof(TValue) * f->sizek +
494                          sizeof(int) * f->sizelineinfo +
495                          sizeof(LocVar) * f->sizelocvars +
496                          sizeof(Upvaldesc) * f->sizeupvalues;
497 }
498 
499 
traverseCclosure(global_State * g,CClosure * cl)500 static lu_mem traverseCclosure (global_State *g, CClosure *cl) {
501   int i;
502   for (i = 0; i < cl->nupvalues; i++)  /* mark its upvalues */
503     markvalue(g, &cl->upvalue[i]);
504   return sizeCclosure(cl->nupvalues);
505 }
506 
507 /*
508 ** open upvalues point to values in a thread, so those values should
509 ** be marked when the thread is traversed except in the atomic phase
510 ** (because then the value cannot be changed by the thread and the
511 ** thread may not be traversed again)
512 */
traverseLclosure(global_State * g,LClosure * cl)513 static lu_mem traverseLclosure (global_State *g, LClosure *cl) {
514   int i;
515   markobjectN(g, cl->p);  /* mark its prototype */
516   for (i = 0; i < cl->nupvalues; i++) {  /* mark its upvalues */
517     UpVal *uv = cl->upvals[i];
518     if (uv != NULL) {
519       if (upisopen(uv) && g->gcstate != GCSinsideatomic)
520         uv->u.open.touched = 1;  /* can be marked in 'remarkupvals' */
521       else
522         markvalue(g, uv->v);
523     }
524   }
525   return sizeLclosure(cl->nupvalues);
526 }
527 
528 
traversethread(global_State * g,lua_State * th)529 static lu_mem traversethread (global_State *g, lua_State *th) {
530   StkId o = th->stack;
531   if (o == NULL)
532     return 1;  /* stack not completely built yet */
533   lua_assert(g->gcstate == GCSinsideatomic ||
534              th->openupval == NULL || isintwups(th));
535   for (; o < th->top; o++)  /* mark live elements in the stack */
536     markvalue(g, o);
537   if (g->gcstate == GCSinsideatomic) {  /* final traversal? */
538     StkId lim = th->stack + th->stacksize;  /* real end of stack */
539     for (; o < lim; o++)  /* clear not-marked stack slice */
540       setnilvalue(o);
541     /* 'remarkupvals' may have removed thread from 'twups' list */
542     if (!isintwups(th) && th->openupval != NULL) {
543       th->twups = g->twups;  /* link it back to the list */
544       g->twups = th;
545     }
546   }
547   else if (g->gckind != KGC_EMERGENCY)
548     luaD_shrinkstack(th); /* do not change stack in emergency cycle */
549   return (sizeof(lua_State) + sizeof(TValue) * th->stacksize);
550 }
551 
552 
553 /*
554 ** traverse one gray object, turning it to black (except for threads,
555 ** which are always gray).
556 */
propagatemark(global_State * g)557 static void propagatemark (global_State *g) {
558   lu_mem size;
559   GCObject *o = g->gray;
560   lua_assert(isgray(o));
561   gray2black(o);
562   switch (o->tt) {
563     case LUA_TTABLE: {
564       Table *h = gco2t(o);
565       g->gray = h->gclist;  /* remove from 'gray' list */
566       size = traversetable(g, h);
567       break;
568     }
569     case LUA_TLCL: {
570       LClosure *cl = gco2lcl(o);
571       g->gray = cl->gclist;  /* remove from 'gray' list */
572       size = traverseLclosure(g, cl);
573       break;
574     }
575     case LUA_TCCL: {
576       CClosure *cl = gco2ccl(o);
577       g->gray = cl->gclist;  /* remove from 'gray' list */
578       size = traverseCclosure(g, cl);
579       break;
580     }
581     case LUA_TTHREAD: {
582       lua_State *th = gco2th(o);
583       g->gray = th->gclist;  /* remove from 'gray' list */
584       linkgclist(th, g->grayagain);  /* insert into 'grayagain' list */
585       black2gray(o);
586       size = traversethread(g, th);
587       break;
588     }
589     case LUA_TPROTO: {
590       Proto *p = gco2p(o);
591       g->gray = p->gclist;  /* remove from 'gray' list */
592       size = traverseproto(g, p);
593       break;
594     }
595     default: lua_assert(0); return;
596   }
597   g->GCmemtrav += size;
598 }
599 
600 
propagateall(global_State * g)601 static void propagateall (global_State *g) {
602   while (g->gray) propagatemark(g);
603 }
604 
605 
convergeephemerons(global_State * g)606 static void convergeephemerons (global_State *g) {
607   int changed;
608   do {
609     GCObject *w;
610     GCObject *next = g->ephemeron;  /* get ephemeron list */
611     g->ephemeron = NULL;  /* tables may return to this list when traversed */
612     changed = 0;
613     while ((w = next) != NULL) {
614       next = gco2t(w)->gclist;
615       if (traverseephemeron(g, gco2t(w))) {  /* traverse marked some value? */
616         propagateall(g);  /* propagate changes */
617         changed = 1;  /* will have to revisit all ephemeron tables */
618       }
619     }
620   } while (changed);
621 }
622 
623 /* }====================================================== */
624 
625 
626 /*
627 ** {======================================================
628 ** Sweep Functions
629 ** =======================================================
630 */
631 
632 
633 /*
634 ** clear entries with unmarked keys from all weaktables in list 'l' up
635 ** to element 'f'
636 */
clearkeys(global_State * g,GCObject * l,GCObject * f)637 static void clearkeys (global_State *g, GCObject *l, GCObject *f) {
638   for (; l != f; l = gco2t(l)->gclist) {
639     Table *h = gco2t(l);
640     Node *n, *limit = gnodelast(h);
641     for (n = gnode(h, 0); n < limit; n++) {
642       if (!ttisnil(gval(n)) && (iscleared(g, gkey(n)))) {
643         setnilvalue(gval(n));  /* remove value ... */
644         removeentry(n);  /* and remove entry from table */
645       }
646     }
647   }
648 }
649 
650 
651 /*
652 ** clear entries with unmarked values from all weaktables in list 'l' up
653 ** to element 'f'
654 */
clearvalues(global_State * g,GCObject * l,GCObject * f)655 static void clearvalues (global_State *g, GCObject *l, GCObject *f) {
656   for (; l != f; l = gco2t(l)->gclist) {
657     Table *h = gco2t(l);
658     Node *n, *limit = gnodelast(h);
659     unsigned int i;
660     for (i = 0; i < h->sizearray; i++) {
661       TValue *o = &h->array[i];
662       if (iscleared(g, o))  /* value was collected? */
663         setnilvalue(o);  /* remove value */
664     }
665     for (n = gnode(h, 0); n < limit; n++) {
666       if (!ttisnil(gval(n)) && iscleared(g, gval(n))) {
667         setnilvalue(gval(n));  /* remove value ... */
668         removeentry(n);  /* and remove entry from table */
669       }
670     }
671   }
672 }
673 
674 
luaC_upvdeccount(lua_State * L,UpVal * uv)675 void luaC_upvdeccount (lua_State *L, UpVal *uv) {
676   lua_assert(uv->refcount > 0);
677   uv->refcount--;
678   if (uv->refcount == 0 && !upisopen(uv))
679     luaM_free(L, uv);
680 }
681 
682 
freeLclosure(lua_State * L,LClosure * cl)683 static void freeLclosure (lua_State *L, LClosure *cl) {
684   int i;
685   for (i = 0; i < cl->nupvalues; i++) {
686     UpVal *uv = cl->upvals[i];
687     if (uv)
688       luaC_upvdeccount(L, uv);
689   }
690   luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
691 }
692 
693 
freeobj(lua_State * L,GCObject * o)694 static void freeobj (lua_State *L, GCObject *o) {
695   switch (o->tt) {
696     case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
697     case LUA_TLCL: {
698       freeLclosure(L, gco2lcl(o));
699       break;
700     }
701     case LUA_TCCL: {
702       luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));
703       break;
704     }
705     case LUA_TTABLE: luaH_free(L, gco2t(o)); break;
706     case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
707     case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
708     case LUA_TSHRSTR:
709       luaS_remove(L, gco2ts(o));  /* remove it from hash table */
710       luaM_freemem(L, o, sizelstring(gco2ts(o)->shrlen));
711       break;
712     case LUA_TLNGSTR: {
713       luaM_freemem(L, o, sizelstring(gco2ts(o)->u.lnglen));
714       break;
715     }
716     default: lua_assert(0);
717   }
718 }
719 
720 
721 #define sweepwholelist(L,p)	sweeplist(L,p,MAX_LUMEM)
722 static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);
723 
724 
725 /*
726 ** sweep at most 'count' elements from a list of GCObjects erasing dead
727 ** objects, where a dead object is one marked with the old (non current)
728 ** white; change all non-dead objects back to white, preparing for next
729 ** collection cycle. Return where to continue the traversal or NULL if
730 ** list is finished.
731 */
sweeplist(lua_State * L,GCObject ** p,lu_mem count)732 static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
733   global_State *g = G(L);
734   int ow = otherwhite(g);
735   int white = luaC_white(g);  /* current white */
736   while (*p != NULL && count-- > 0) {
737     GCObject *curr = *p;
738     int marked = curr->marked;
739     if (isdeadm(ow, marked)) {  /* is 'curr' dead? */
740       *p = curr->next;  /* remove 'curr' from list */
741       freeobj(L, curr);  /* erase 'curr' */
742     }
743     else {  /* change mark to 'white' */
744       curr->marked = cast_byte((marked & maskcolors) | white);
745       p = &curr->next;  /* go to next element */
746     }
747   }
748   return (*p == NULL) ? NULL : p;
749 }
750 
751 
752 /*
753 ** sweep a list until a live object (or end of list)
754 */
sweeptolive(lua_State * L,GCObject ** p,int * n)755 static GCObject **sweeptolive (lua_State *L, GCObject **p, int *n) {
756   GCObject **old = p;
757   int i = 0;
758   do {
759     i++;
760     p = sweeplist(L, p, 1);
761   } while (p == old);
762   if (n) *n += i;
763   return p;
764 }
765 
766 /* }====================================================== */
767 
768 
769 /*
770 ** {======================================================
771 ** Finalization
772 ** =======================================================
773 */
774 
775 /*
776 ** If possible, free concatenation buffer and shrink string table
777 */
checkSizes(lua_State * L,global_State * g)778 static void checkSizes (lua_State *L, global_State *g) {
779   if (g->gckind != KGC_EMERGENCY) {
780     l_mem olddebt = g->GCdebt;
781     luaZ_freebuffer(L, &g->buff);  /* free concatenation buffer */
782     if (g->strt.nuse < g->strt.size / 4)  /* string table too big? */
783       luaS_resize(L, g->strt.size / 2);  /* shrink it a little */
784     g->GCestimate += g->GCdebt - olddebt;  /* update estimate */
785   }
786 }
787 
788 
udata2finalize(global_State * g)789 static GCObject *udata2finalize (global_State *g) {
790   GCObject *o = g->tobefnz;  /* get first element */
791   lua_assert(tofinalize(o));
792   g->tobefnz = o->next;  /* remove it from 'tobefnz' list */
793   o->next = g->allgc;  /* return it to 'allgc' list */
794   g->allgc = o;
795   resetbit(o->marked, FINALIZEDBIT);  /* object is "normal" again */
796   if (issweepphase(g))
797     makewhite(g, o);  /* "sweep" object */
798   return o;
799 }
800 
801 
dothecall(lua_State * L,void * ud)802 static void dothecall (lua_State *L, void *ud) {
803   UNUSED(ud);
804   luaD_call(L, L->top - 2, 0, 0);
805 }
806 
807 
GCTM(lua_State * L,int propagateerrors)808 static void GCTM (lua_State *L, int propagateerrors) {
809   global_State *g = G(L);
810   const TValue *tm;
811   TValue v;
812   setgcovalue(L, &v, udata2finalize(g));
813   tm = luaT_gettmbyobj(L, &v, TM_GC);
814   if (tm != NULL && ttisfunction(tm)) {  /* is there a finalizer? */
815     int status;
816     lu_byte oldah = L->allowhook;
817     int running  = g->gcrunning;
818     L->allowhook = 0;  /* stop debug hooks during GC metamethod */
819     g->gcrunning = 0;  /* avoid GC steps */
820     setobj2s(L, L->top, tm);  /* push finalizer... */
821     setobj2s(L, L->top + 1, &v);  /* ... and its argument */
822     L->top += 2;  /* and (next line) call the finalizer */
823     status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
824     L->allowhook = oldah;  /* restore hooks */
825     g->gcrunning = running;  /* restore state */
826     if (status != LUA_OK && propagateerrors) {  /* error while running __gc? */
827       if (status == LUA_ERRRUN) {  /* is there an error object? */
828         const char *msg = (ttisstring(L->top - 1))
829                             ? svalue(L->top - 1)
830                             : "no message";
831         luaO_pushfstring(L, "error in __gc metamethod (%s)", msg);
832         status = LUA_ERRGCMM;  /* error in __gc metamethod */
833       }
834       luaD_throw(L, status);  /* re-throw error */
835     }
836   }
837 }
838 
839 
840 /*
841 ** call a few (up to 'g->gcfinnum') finalizers
842 */
runafewfinalizers(lua_State * L)843 static int runafewfinalizers (lua_State *L) {
844   global_State *g = G(L);
845   unsigned int i;
846   lua_assert(!g->tobefnz || g->gcfinnum > 0);
847   for (i = 0; g->tobefnz && i < g->gcfinnum; i++)
848     GCTM(L, 1);  /* call one finalizer */
849   g->gcfinnum = (!g->tobefnz) ? 0  /* nothing more to finalize? */
850                     : g->gcfinnum * 2;  /* else call a few more next time */
851   return i;
852 }
853 
854 
855 /*
856 ** call all pending finalizers
857 */
callallpendingfinalizers(lua_State * L,int propagateerrors)858 static void callallpendingfinalizers (lua_State *L, int propagateerrors) {
859   global_State *g = G(L);
860   while (g->tobefnz)
861     GCTM(L, propagateerrors);
862 }
863 
864 
865 /*
866 ** find last 'next' field in list 'p' list (to add elements in its end)
867 */
findlast(GCObject ** p)868 static GCObject **findlast (GCObject **p) {
869   while (*p != NULL)
870     p = &(*p)->next;
871   return p;
872 }
873 
874 
875 /*
876 ** move all unreachable objects (or 'all' objects) that need
877 ** finalization from list 'finobj' to list 'tobefnz' (to be finalized)
878 */
separatetobefnz(global_State * g,int all)879 static void separatetobefnz (global_State *g, int all) {
880   GCObject *curr;
881   GCObject **p = &g->finobj;
882   GCObject **lastnext = findlast(&g->tobefnz);
883   while ((curr = *p) != NULL) {  /* traverse all finalizable objects */
884     lua_assert(tofinalize(curr));
885     if (!(iswhite(curr) || all))  /* not being collected? */
886       p = &curr->next;  /* don't bother with it */
887     else {
888       *p = curr->next;  /* remove 'curr' from 'finobj' list */
889       curr->next = *lastnext;  /* link at the end of 'tobefnz' list */
890       *lastnext = curr;
891       lastnext = &curr->next;
892     }
893   }
894 }
895 
896 
897 /*
898 ** if object 'o' has a finalizer, remove it from 'allgc' list (must
899 ** search the list to find it) and link it in 'finobj' list.
900 */
luaC_checkfinalizer(lua_State * L,GCObject * o,Table * mt)901 void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
902   global_State *g = G(L);
903   if (tofinalize(o) ||                 /* obj. is already marked... */
904       gfasttm(g, mt, TM_GC) == NULL)   /* or has no finalizer? */
905     return;  /* nothing to be done */
906   else {  /* move 'o' to 'finobj' list */
907     GCObject **p;
908     if (issweepphase(g)) {
909       makewhite(g, o);  /* "sweep" object 'o' */
910       if (g->sweepgc == &o->next)  /* should not remove 'sweepgc' object */
911         g->sweepgc = sweeptolive(L, g->sweepgc, NULL);  /* change 'sweepgc' */
912     }
913     /* search for pointer pointing to 'o' */
914     for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
915     *p = o->next;  /* remove 'o' from 'allgc' list */
916     o->next = g->finobj;  /* link it in 'finobj' list */
917     g->finobj = o;
918     l_setbit(o->marked, FINALIZEDBIT);  /* mark it as such */
919   }
920 }
921 
922 /* }====================================================== */
923 
924 
925 
926 /*
927 ** {======================================================
928 ** GC control
929 ** =======================================================
930 */
931 
932 
933 /*
934 ** Set a reasonable "time" to wait before starting a new GC cycle; cycle
935 ** will start when memory use hits threshold. (Division by 'estimate'
936 ** should be OK: it cannot be zero (because Lua cannot even start with
937 ** less than PAUSEADJ bytes).
938 */
setpause(global_State * g)939 static void setpause (global_State *g) {
940   l_mem threshold, debt;
941   l_mem estimate = g->GCestimate / PAUSEADJ;  /* adjust 'estimate' */
942   lua_assert(estimate > 0);
943   threshold = (g->gcpause < MAX_LMEM / estimate)  /* overflow? */
944             ? estimate * g->gcpause  /* no overflow */
945             : MAX_LMEM;  /* overflow; truncate to maximum */
946   debt = gettotalbytes(g) - threshold;
947   luaE_setdebt(g, debt);
948 }
949 
950 
951 /*
952 ** Enter first sweep phase.
953 ** The call to 'sweeptolive' makes pointer point to an object inside
954 ** the list (instead of to the header), so that the real sweep do not
955 ** need to skip objects created between "now" and the start of the real
956 ** sweep.
957 ** Returns how many objects it swept.
958 */
entersweep(lua_State * L)959 static int entersweep (lua_State *L) {
960   global_State *g = G(L);
961   int n = 0;
962   g->gcstate = GCSswpallgc;
963   lua_assert(g->sweepgc == NULL);
964   g->sweepgc = sweeptolive(L, &g->allgc, &n);
965   return n;
966 }
967 
968 
luaC_freeallobjects(lua_State * L)969 void luaC_freeallobjects (lua_State *L) {
970   global_State *g = G(L);
971   separatetobefnz(g, 1);  /* separate all objects with finalizers */
972   lua_assert(g->finobj == NULL);
973   callallpendingfinalizers(L, 0);
974   lua_assert(g->tobefnz == NULL);
975   g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */
976   g->gckind = KGC_NORMAL;
977   sweepwholelist(L, &g->finobj);
978   sweepwholelist(L, &g->allgc);
979   sweepwholelist(L, &g->fixedgc);  /* collect fixed objects */
980   lua_assert(g->strt.nuse == 0);
981 }
982 
983 
atomic(lua_State * L)984 static l_mem atomic (lua_State *L) {
985   global_State *g = G(L);
986   l_mem work;
987   GCObject *origweak, *origall;
988   GCObject *grayagain = g->grayagain;  /* save original list */
989   lua_assert(g->ephemeron == NULL && g->weak == NULL);
990   lua_assert(!iswhite(g->mainthread));
991   g->gcstate = GCSinsideatomic;
992   g->GCmemtrav = 0;  /* start counting work */
993   markobject(g, L);  /* mark running thread */
994   /* registry and global metatables may be changed by API */
995   markvalue(g, &g->l_registry);
996   markmt(g);  /* mark global metatables */
997   /* remark occasional upvalues of (maybe) dead threads */
998   remarkupvals(g);
999   propagateall(g);  /* propagate changes */
1000   work = g->GCmemtrav;  /* stop counting (do not recount 'grayagain') */
1001   g->gray = grayagain;
1002   propagateall(g);  /* traverse 'grayagain' list */
1003   g->GCmemtrav = 0;  /* restart counting */
1004   convergeephemerons(g);
1005   /* at this point, all strongly accessible objects are marked. */
1006   /* Clear values from weak tables, before checking finalizers */
1007   clearvalues(g, g->weak, NULL);
1008   clearvalues(g, g->allweak, NULL);
1009   origweak = g->weak; origall = g->allweak;
1010   work += g->GCmemtrav;  /* stop counting (objects being finalized) */
1011   separatetobefnz(g, 0);  /* separate objects to be finalized */
1012   g->gcfinnum = 1;  /* there may be objects to be finalized */
1013   markbeingfnz(g);  /* mark objects that will be finalized */
1014   propagateall(g);  /* remark, to propagate 'resurrection' */
1015   g->GCmemtrav = 0;  /* restart counting */
1016   convergeephemerons(g);
1017   /* at this point, all resurrected objects are marked. */
1018   /* remove dead objects from weak tables */
1019   clearkeys(g, g->ephemeron, NULL);  /* clear keys from all ephemeron tables */
1020   clearkeys(g, g->allweak, NULL);  /* clear keys from all 'allweak' tables */
1021   /* clear values from resurrected weak tables */
1022   clearvalues(g, g->weak, origweak);
1023   clearvalues(g, g->allweak, origall);
1024   luaS_clearcache(g);
1025   g->currentwhite = cast_byte(otherwhite(g));  /* flip current white */
1026   work += g->GCmemtrav;  /* complete counting */
1027   return work;  /* estimate of memory marked by 'atomic' */
1028 }
1029 
1030 
sweepstep(lua_State * L,global_State * g,int nextstate,GCObject ** nextlist)1031 static lu_mem sweepstep (lua_State *L, global_State *g,
1032                          int nextstate, GCObject **nextlist) {
1033   if (g->sweepgc) {
1034     l_mem olddebt = g->GCdebt;
1035     g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
1036     g->GCestimate += g->GCdebt - olddebt;  /* update estimate */
1037     if (g->sweepgc)  /* is there still something to sweep? */
1038       return (GCSWEEPMAX * GCSWEEPCOST);
1039   }
1040   /* else enter next state */
1041   g->gcstate = nextstate;
1042   g->sweepgc = nextlist;
1043   return 0;
1044 }
1045 
1046 
singlestep(lua_State * L)1047 static lu_mem singlestep (lua_State *L) {
1048   global_State *g = G(L);
1049   switch (g->gcstate) {
1050     case GCSpause: {
1051       g->GCmemtrav = g->strt.size * sizeof(GCObject*);
1052       restartcollection(g);
1053       g->gcstate = GCSpropagate;
1054       return g->GCmemtrav;
1055     }
1056     case GCSpropagate: {
1057       g->GCmemtrav = 0;
1058       lua_assert(g->gray);
1059       propagatemark(g);
1060        if (g->gray == NULL)  /* no more gray objects? */
1061         g->gcstate = GCSatomic;  /* finish propagate phase */
1062       return g->GCmemtrav;  /* memory traversed in this step */
1063     }
1064     case GCSatomic: {
1065       lu_mem work;
1066       int sw;
1067       propagateall(g);  /* make sure gray list is empty */
1068       work = atomic(L);  /* work is what was traversed by 'atomic' */
1069       sw = entersweep(L);
1070       g->GCestimate = gettotalbytes(g);  /* first estimate */;
1071       return work + sw * GCSWEEPCOST;
1072     }
1073     case GCSswpallgc: {  /* sweep "regular" objects */
1074       return sweepstep(L, g, GCSswpfinobj, &g->finobj);
1075     }
1076     case GCSswpfinobj: {  /* sweep objects with finalizers */
1077       return sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
1078     }
1079     case GCSswptobefnz: {  /* sweep objects to be finalized */
1080       return sweepstep(L, g, GCSswpend, NULL);
1081     }
1082     case GCSswpend: {  /* finish sweeps */
1083       makewhite(g, g->mainthread);  /* sweep main thread */
1084       checkSizes(L, g);
1085       g->gcstate = GCScallfin;
1086       return 0;
1087     }
1088     case GCScallfin: {  /* call remaining finalizers */
1089       if (g->tobefnz && g->gckind != KGC_EMERGENCY) {
1090         int n = runafewfinalizers(L);
1091         return (n * GCFINALIZECOST);
1092       }
1093       else {  /* emergency mode or no more finalizers */
1094         g->gcstate = GCSpause;  /* finish collection */
1095         return 0;
1096       }
1097     }
1098     default: lua_assert(0); return 0;
1099   }
1100 }
1101 
1102 
1103 /*
1104 ** advances the garbage collector until it reaches a state allowed
1105 ** by 'statemask'
1106 */
luaC_runtilstate(lua_State * L,int statesmask)1107 void luaC_runtilstate (lua_State *L, int statesmask) {
1108   global_State *g = G(L);
1109   while (!testbit(statesmask, g->gcstate))
1110     singlestep(L);
1111 }
1112 
1113 
1114 /*
1115 ** get GC debt and convert it from Kb to 'work units' (avoid zero debt
1116 ** and overflows)
1117 */
getdebt(global_State * g)1118 static l_mem getdebt (global_State *g) {
1119   l_mem debt = g->GCdebt;
1120   int stepmul = g->gcstepmul;
1121   debt = (debt / STEPMULADJ) + 1;
1122   debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM;
1123   return debt;
1124 }
1125 
1126 /*
1127 ** performs a basic GC step when collector is running
1128 */
luaC_step(lua_State * L)1129 void luaC_step (lua_State *L) {
1130   global_State *g = G(L);
1131   l_mem debt = getdebt(g);  /* GC deficit (be paid now) */
1132   if (!g->gcrunning) {  /* not running? */
1133     luaE_setdebt(g, -GCSTEPSIZE * 10);  /* avoid being called too often */
1134     return;
1135   }
1136   do {  /* repeat until pause or enough "credit" (negative debt) */
1137     lu_mem work = singlestep(L);  /* perform one single step */
1138     debt -= work;
1139   } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);
1140   if (g->gcstate == GCSpause)
1141     setpause(g);  /* pause until next cycle */
1142   else {
1143     debt = (debt / g->gcstepmul) * STEPMULADJ;  /* convert 'work units' to Kb */
1144     luaE_setdebt(g, debt);
1145     runafewfinalizers(L);
1146   }
1147 }
1148 
1149 
1150 /*
1151 ** Performs a full GC cycle; if 'isemergency', set a flag to avoid
1152 ** some operations which could change the interpreter state in some
1153 ** unexpected ways (running finalizers and shrinking some structures).
1154 ** Before running the collection, check 'keepinvariant'; if it is true,
1155 ** there may be some objects marked as black, so the collector has
1156 ** to sweep all objects to turn them back to white (as white has not
1157 ** changed, nothing will be collected).
1158 */
luaC_fullgc(lua_State * L,int isemergency)1159 void luaC_fullgc (lua_State *L, int isemergency) {
1160   global_State *g = G(L);
1161   lua_assert(g->gckind == KGC_NORMAL);
1162   if (isemergency) g->gckind = KGC_EMERGENCY;  /* set flag */
1163   if (keepinvariant(g)) {  /* black objects? */
1164     entersweep(L); /* sweep everything to turn them back to white */
1165   }
1166   /* finish any pending sweep phase to start a new cycle */
1167   luaC_runtilstate(L, bitmask(GCSpause));
1168   luaC_runtilstate(L, ~bitmask(GCSpause));  /* start new collection */
1169   luaC_runtilstate(L, bitmask(GCScallfin));  /* run up to finalizers */
1170   /* estimate must be correct after a full GC cycle */
1171   lua_assert(g->GCestimate == gettotalbytes(g));
1172   luaC_runtilstate(L, bitmask(GCSpause));  /* finish collection */
1173   g->gckind = KGC_NORMAL;
1174   setpause(g);
1175 }
1176 
1177 /* }====================================================== */
1178 
1179 
1180