2 ** $Id: lgc.c,v 2.215 2016/12/22 13:08:50 roberto Exp $
4 ** See Copyright Notice in lua.h
30 ** internal state for collector while inside the atomic phase. The
31 ** collector should never be in this state while running regular code.
33 #define GCSinsideatomic (GCSpause + 1)
36 ** cost of sweeping one element (the size of a small object divided
37 ** by some adjust for the sweep speed)
39 #define GCSWEEPCOST ((sizeof(TString) + 4) / 4)
41 /* maximum number of elements to sweep in each single step */
42 #define GCSWEEPMAX (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4))
44 /* cost of calling one finalizer */
45 #define GCFINALIZECOST GCSWEEPCOST
49 ** macro to adjust 'stepmul': 'stepmul' is actually used like
50 ** 'stepmul / STEPMULADJ' (value chosen by tests)
52 #define STEPMULADJ 200
56 ** macro to adjust 'pause': 'pause' is actually used like
57 ** 'pause / PAUSEADJ' (value chosen by tests)
63 ** 'makewhite' erases all color bits then sets only the current white
66 #define maskcolors (~(bitmask(BLACKBIT) | WHITEBITS))
67 #define makewhite(g,x) \
68 (x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g)))
70 #define white2gray(x) resetbits(x->marked, WHITEBITS)
71 #define black2gray(x) resetbit(x->marked, BLACKBIT)
74 #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
76 #define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))
79 #define checkconsistency(obj) \
80 lua_longassert(!iscollectable(obj) || righttt(obj))
83 #define markvalue(g,o) { checkconsistency(o); \
84 if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
86 #define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); }
89 ** mark an object that can be NULL (either because it is really optional,
90 ** or it was stripped as debug info, or inside an uncompleted structure)
92 #define markobjectN(g,t) { if (t) markobject(g,t); }
94 static void reallymarkobject (global_State *g, GCObject *o);
98 ** {======================================================
100 ** =======================================================
105 ** one after last element in a hash array
107 #define gnodelast(h) gnode(h, cast(size_t, sizenode(h)))
111 ** link collectable object 'o' into list pointed by 'p'
113 #define linkgclist(o,p) ((o)->gclist = (p), (p) = obj2gco(o))
117 ** If key is not marked, mark its entry as dead. This allows key to be
118 ** collected, but keeps its entry in the table. A dead node is needed
119 ** when Lua looks up for a key (it may be part of a chain) and when
120 ** traversing a weak table (key might be removed from the table during
121 ** traversal). Other places never manipulate dead keys, because its
122 ** associated nil value is enough to signal that the entry is logically
125 static void removeentry (Node *n) {
126 lua_assert(ttisnil(gval(n)));
127 if (valiswhite(gkey(n)))
128 setdeadvalue(wgkey(n)); /* unused and unmarked key; remove it */
133 ** tells whether a key or value can be cleared from a weak
134 ** table. Non-collectable objects are never removed from weak
135 ** tables. Strings behave as 'values', so are never removed too. for
136 ** other objects: if really collected, cannot keep them; for objects
137 ** being finalized, keep them in keys, but not in values
139 static int iscleared (global_State *g, const TValue *o) {
140 if (!iscollectable(o)) return 0;
141 else if (ttisstring(o)) {
142 markobject(g, tsvalue(o)); /* strings are 'values', so are never weak */
145 else return iswhite(gcvalue(o));
150 ** barrier that moves collector forward, that is, mark the white object
151 ** being pointed by a black object. (If in sweep phase, clear the black
152 ** object to white [sweep it] to avoid other barrier calls for this
155 void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
156 global_State *g = G(L);
157 lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
158 if (keepinvariant(g)) /* must keep invariant? */
159 reallymarkobject(g, v); /* restore invariant */
160 else { /* sweep phase */
161 lua_assert(issweepphase(g));
162 makewhite(g, o); /* mark main obj. as white to avoid other barriers */
168 ** barrier that moves collector backward, that is, mark the black object
169 ** pointing to a white object as gray again.
171 void luaC_barrierback_ (lua_State *L, Table *t) {
172 global_State *g = G(L);
173 lua_assert(isblack(t) && !isdead(g, t));
174 black2gray(t); /* make table gray (again) */
175 linkgclist(t, g->grayagain);
180 ** barrier for assignments to closed upvalues. Because upvalues are
181 ** shared among closures, it is impossible to know the color of all
182 ** closures pointing to it. So, we assume that the object being assigned
185 void luaC_upvalbarrier_ (lua_State *L, UpVal *uv) {
186 global_State *g = G(L);
187 GCObject *o = gcvalue(uv->v);
188 lua_assert(!upisopen(uv)); /* ensured by macro luaC_upvalbarrier */
189 if (keepinvariant(g))
194 void luaC_fix (lua_State *L, GCObject *o) {
195 global_State *g = G(L);
196 lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */
197 white2gray(o); /* they will be gray forever */
198 g->allgc = o->next; /* remove object from 'allgc' list */
199 o->next = g->fixedgc; /* link it to 'fixedgc' list */
205 ** create a new collectable object (with given type and size) and link
206 ** it to 'allgc' list.
208 GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
209 global_State *g = G(L);
210 GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz));
211 o->marked = luaC_white(g);
218 /* }====================================================== */
223 ** {======================================================
225 ** =======================================================
230 ** mark an object. Userdata, strings, and closed upvalues are visited
231 ** and turned black here. Other objects are marked gray and added
232 ** to appropriate list to be visited (and turned black) later. (Open
233 ** upvalues are already linked in 'headuv' list.)
235 static void reallymarkobject (global_State *g, GCObject *o) {
241 g->GCmemtrav += sizelstring(gco2ts(o)->shrlen);
246 g->GCmemtrav += sizelstring(gco2ts(o)->u.lnglen);
249 case LUA_TUSERDATA: {
251 markobjectN(g, gco2u(o)->metatable); /* mark its metatable */
253 g->GCmemtrav += sizeudata(gco2u(o));
254 getuservalue(g->mainthread, gco2u(o), &uvalue);
255 if (valiswhite(&uvalue)) { /* markvalue(g, &uvalue); */
256 o = gcvalue(&uvalue);
262 linkgclist(gco2lcl(o), g->gray);
266 linkgclist(gco2ccl(o), g->gray);
270 linkgclist(gco2t(o), g->gray);
274 linkgclist(gco2th(o), g->gray);
278 linkgclist(gco2p(o), g->gray);
281 default: lua_assert(0); break;
287 ** mark metamethods for basic types
289 static void markmt (global_State *g) {
291 for (i=0; i < LUA_NUMTAGS; i++)
292 markobjectN(g, g->mt[i]);
297 ** mark all objects in list of being-finalized
299 static void markbeingfnz (global_State *g) {
301 for (o = g->tobefnz; o != NULL; o = o->next)
307 ** Mark all values stored in marked open upvalues from non-marked threads.
308 ** (Values from marked threads were already marked when traversing the
309 ** thread.) Remove from the list threads that no longer have upvalues and
310 ** not-marked threads.
312 static void remarkupvals (global_State *g) {
314 lua_State **p = &g->twups;
315 while ((thread = *p) != NULL) {
316 lua_assert(!isblack(thread)); /* threads are never black */
317 if (isgray(thread) && thread->openupval != NULL)
318 p = &thread->twups; /* keep marked thread with upvalues in the list */
319 else { /* thread is not marked or without upvalues */
321 *p = thread->twups; /* remove thread from the list */
322 thread->twups = thread; /* mark that it is out of list */
323 for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {
324 if (uv->u.open.touched) {
325 markvalue(g, uv->v); /* remark upvalue's value */
326 uv->u.open.touched = 0;
335 ** mark root set and reset all gray lists, to start a new collection
337 static void restartcollection (global_State *g) {
338 g->gray = g->grayagain = NULL;
339 g->weak = g->allweak = g->ephemeron = NULL;
340 markobject(g, g->mainthread);
341 markvalue(g, &g->l_registry);
343 markbeingfnz(g); /* mark any finalizing object left from previous cycle */
346 /* }====================================================== */
350 ** {======================================================
351 ** Traverse functions
352 ** =======================================================
356 ** Traverse a table with weak values and link it to proper list. During
357 ** propagate phase, keep it in 'grayagain' list, to be revisited in the
358 ** atomic phase. In the atomic phase, if table has any white value,
359 ** put it in 'weak' list, to be cleared.
361 static void traverseweakvalue (global_State *g, Table *h) {
362 Node *n, *limit = gnodelast(h);
363 /* if there is array part, assume it may have white values (it is not
364 worth traversing it now just to check) */
365 int hasclears = (h->sizearray > 0);
366 for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
368 if (ttisnil(gval(n))) /* entry is empty? */
369 removeentry(n); /* remove it */
371 lua_assert(!ttisnil(gkey(n)));
372 markvalue(g, gkey(n)); /* mark key */
373 if (!hasclears && iscleared(g, gval(n))) /* is there a white value? */
374 hasclears = 1; /* table will have to be cleared */
377 if (g->gcstate == GCSpropagate)
378 linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
380 linkgclist(h, g->weak); /* has to be cleared later */
385 ** Traverse an ephemeron table and link it to proper list. Returns true
386 ** iff any object was marked during this traversal (which implies that
387 ** convergence has to continue). During propagation phase, keep table
388 ** in 'grayagain' list, to be visited again in the atomic phase. In
389 ** the atomic phase, if table has any white->white entry, it has to
390 ** be revisited during ephemeron convergence (as that key may turn
391 ** black). Otherwise, if it has any white key, table has to be cleared
392 ** (in the atomic phase).
394 static int traverseephemeron (global_State *g, Table *h) {
395 int marked = 0; /* true if an object is marked in this traversal */
396 int hasclears = 0; /* true if table has white keys */
397 int hasww = 0; /* true if table has entry "white-key -> white-value" */
398 Node *n, *limit = gnodelast(h);
400 /* traverse array part */
401 for (i = 0; i < h->sizearray; i++) {
402 if (valiswhite(&h->array[i])) {
404 reallymarkobject(g, gcvalue(&h->array[i]));
407 /* traverse hash part */
408 for (n = gnode(h, 0); n < limit; n++) {
410 if (ttisnil(gval(n))) /* entry is empty? */
411 removeentry(n); /* remove it */
412 else if (iscleared(g, gkey(n))) { /* key is not marked (yet)? */
413 hasclears = 1; /* table must be cleared */
414 if (valiswhite(gval(n))) /* value not marked yet? */
415 hasww = 1; /* white-white entry */
417 else if (valiswhite(gval(n))) { /* value not marked yet? */
419 reallymarkobject(g, gcvalue(gval(n))); /* mark it now */
422 /* link table into proper list */
423 if (g->gcstate == GCSpropagate)
424 linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
425 else if (hasww) /* table has white->white entries? */
426 linkgclist(h, g->ephemeron); /* have to propagate again */
427 else if (hasclears) /* table has white keys? */
428 linkgclist(h, g->allweak); /* may have to clean white keys */
433 static void traversestrongtable (global_State *g, Table *h) {
434 Node *n, *limit = gnodelast(h);
436 for (i = 0; i < h->sizearray; i++) /* traverse array part */
437 markvalue(g, &h->array[i]);
438 for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
440 if (ttisnil(gval(n))) /* entry is empty? */
441 removeentry(n); /* remove it */
443 lua_assert(!ttisnil(gkey(n)));
444 markvalue(g, gkey(n)); /* mark key */
445 markvalue(g, gval(n)); /* mark value */
451 static lu_mem traversetable (global_State *g, Table *h) {
452 const char *weakkey, *weakvalue;
453 const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
454 markobjectN(g, h->metatable);
455 if (mode && ttisstring(mode) && /* is there a weak mode? */
456 ((weakkey = strchr(svalue(mode), 'k')),
457 (weakvalue = strchr(svalue(mode), 'v')),
458 (weakkey || weakvalue))) { /* is really weak? */
459 black2gray(h); /* keep table gray */
460 if (!weakkey) /* strong keys? */
461 traverseweakvalue(g, h);
462 else if (!weakvalue) /* strong values? */
463 traverseephemeron(g, h);
465 linkgclist(h, g->allweak); /* nothing to traverse now */
468 traversestrongtable(g, h);
469 return sizeof(Table) + sizeof(TValue) * h->sizearray +
470 sizeof(Node) * cast(size_t, allocsizenode(h));
475 ** Traverse a prototype. (While a prototype is being build, its
476 ** arrays can be larger than needed; the extra slots are filled with
477 ** NULL, so the use of 'markobjectN')
479 static int traverseproto (global_State *g, Proto *f) {
481 if (f->cache && iswhite(f->cache))
482 f->cache = NULL; /* allow cache to be collected */
483 markobjectN(g, f->source);
484 for (i = 0; i < f->sizek; i++) /* mark literals */
485 markvalue(g, &f->k[i]);
486 for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
487 markobjectN(g, f->upvalues[i].name);
488 for (i = 0; i < f->sizep; i++) /* mark nested protos */
489 markobjectN(g, f->p[i]);
490 for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
491 markobjectN(g, f->locvars[i].varname);
492 return sizeof(Proto) + sizeof(Instruction) * f->sizecode +
493 sizeof(Proto *) * f->sizep +
494 sizeof(TValue) * f->sizek +
495 sizeof(int) * f->sizelineinfo +
496 sizeof(LocVar) * f->sizelocvars +
497 sizeof(Upvaldesc) * f->sizeupvalues;
501 static lu_mem traverseCclosure (global_State *g, CClosure *cl) {
503 for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */
504 markvalue(g, &cl->upvalue[i]);
505 return sizeCclosure(cl->nupvalues);
509 ** open upvalues point to values in a thread, so those values should
510 ** be marked when the thread is traversed except in the atomic phase
511 ** (because then the value cannot be changed by the thread and the
512 ** thread may not be traversed again)
514 static lu_mem traverseLclosure (global_State *g, LClosure *cl) {
516 markobjectN(g, cl->p); /* mark its prototype */
517 for (i = 0; i < cl->nupvalues; i++) { /* mark its upvalues */
518 UpVal *uv = cl->upvals[i];
520 if (upisopen(uv) && g->gcstate != GCSinsideatomic)
521 uv->u.open.touched = 1; /* can be marked in 'remarkupvals' */
526 return sizeLclosure(cl->nupvalues);
530 static lu_mem traversethread (global_State *g, lua_State *th) {
533 return 1; /* stack not completely built yet */
534 lua_assert(g->gcstate == GCSinsideatomic ||
535 th->openupval == NULL || isintwups(th));
536 for (; o < th->top; o++) /* mark live elements in the stack */
538 if (g->gcstate == GCSinsideatomic) { /* final traversal? */
539 StkId lim = th->stack + th->stacksize; /* real end of stack */
540 for (; o < lim; o++) /* clear not-marked stack slice */
542 /* 'remarkupvals' may have removed thread from 'twups' list */
543 if (!isintwups(th) && th->openupval != NULL) {
544 th->twups = g->twups; /* link it back to the list */
548 else if (g->gckind != KGC_EMERGENCY)
549 luaD_shrinkstack(th); /* do not change stack in emergency cycle */
550 return (sizeof(lua_State) + sizeof(TValue) * th->stacksize +
551 sizeof(CallInfo) * th->nci);
556 ** traverse one gray object, turning it to black (except for threads,
557 ** which are always gray).
559 static void propagatemark (global_State *g) {
561 GCObject *o = g->gray;
562 lua_assert(isgray(o));
567 g->gray = h->gclist; /* remove from 'gray' list */
568 size = traversetable(g, h);
572 LClosure *cl = gco2lcl(o);
573 g->gray = cl->gclist; /* remove from 'gray' list */
574 size = traverseLclosure(g, cl);
578 CClosure *cl = gco2ccl(o);
579 g->gray = cl->gclist; /* remove from 'gray' list */
580 size = traverseCclosure(g, cl);
584 lua_State *th = gco2th(o);
585 g->gray = th->gclist; /* remove from 'gray' list */
586 linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
588 size = traversethread(g, th);
593 g->gray = p->gclist; /* remove from 'gray' list */
594 size = traverseproto(g, p);
597 default: lua_assert(0); return;
599 g->GCmemtrav += size;
603 static void propagateall (global_State *g) {
604 while (g->gray) propagatemark(g);
608 static void convergeephemerons (global_State *g) {
612 GCObject *next = g->ephemeron; /* get ephemeron list */
613 g->ephemeron = NULL; /* tables may return to this list when traversed */
615 while ((w = next) != NULL) {
616 next = gco2t(w)->gclist;
617 if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */
618 propagateall(g); /* propagate changes */
619 changed = 1; /* will have to revisit all ephemeron tables */
625 /* }====================================================== */
629 ** {======================================================
631 ** =======================================================
636 ** clear entries with unmarked keys from all weaktables in list 'l' up
639 static void clearkeys (global_State *g, GCObject *l, GCObject *f) {
640 for (; l != f; l = gco2t(l)->gclist) {
642 Node *n, *limit = gnodelast(h);
643 for (n = gnode(h, 0); n < limit; n++) {
644 if (!ttisnil(gval(n)) && (iscleared(g, gkey(n)))) {
645 setnilvalue(gval(n)); /* remove value ... */
646 removeentry(n); /* and remove entry from table */
654 ** clear entries with unmarked values from all weaktables in list 'l' up
657 static void clearvalues (global_State *g, GCObject *l, GCObject *f) {
658 for (; l != f; l = gco2t(l)->gclist) {
660 Node *n, *limit = gnodelast(h);
662 for (i = 0; i < h->sizearray; i++) {
663 TValue *o = &h->array[i];
664 if (iscleared(g, o)) /* value was collected? */
665 setnilvalue(o); /* remove value */
667 for (n = gnode(h, 0); n < limit; n++) {
668 if (!ttisnil(gval(n)) && iscleared(g, gval(n))) {
669 setnilvalue(gval(n)); /* remove value ... */
670 removeentry(n); /* and remove entry from table */
677 void luaC_upvdeccount (lua_State *L, UpVal *uv) {
678 lua_assert(uv->refcount > 0);
680 if (uv->refcount == 0 && !upisopen(uv))
685 static void freeLclosure (lua_State *L, LClosure *cl) {
687 for (i = 0; i < cl->nupvalues; i++) {
688 UpVal *uv = cl->upvals[i];
690 luaC_upvdeccount(L, uv);
692 luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
696 static void freeobj (lua_State *L, GCObject *o) {
698 case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
700 freeLclosure(L, gco2lcl(o));
704 luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));
707 case LUA_TTABLE: luaH_free(L, gco2t(o)); break;
708 case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
709 case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
711 luaS_remove(L, gco2ts(o)); /* remove it from hash table */
712 luaM_freemem(L, o, sizelstring(gco2ts(o)->shrlen));
715 luaM_freemem(L, o, sizelstring(gco2ts(o)->u.lnglen));
718 default: lua_assert(0);
723 #define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM)
724 static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);
728 ** sweep at most 'count' elements from a list of GCObjects erasing dead
729 ** objects, where a dead object is one marked with the old (non current)
730 ** white; change all non-dead objects back to white, preparing for next
731 ** collection cycle. Return where to continue the traversal or NULL if
734 static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
735 global_State *g = G(L);
736 int ow = otherwhite(g);
737 int white = luaC_white(g); /* current white */
738 while (*p != NULL && count-- > 0) {
740 int marked = curr->marked;
741 if (isdeadm(ow, marked)) { /* is 'curr' dead? */
742 *p = curr->next; /* remove 'curr' from list */
743 freeobj(L, curr); /* erase 'curr' */
745 else { /* change mark to 'white' */
746 curr->marked = cast_byte((marked & maskcolors) | white);
747 p = &curr->next; /* go to next element */
750 return (*p == NULL) ? NULL : p;
755 ** sweep a list until a live object (or end of list)
757 static GCObject **sweeptolive (lua_State *L, GCObject **p) {
760 p = sweeplist(L, p, 1);
765 /* }====================================================== */
769 ** {======================================================
771 ** =======================================================
775 ** If possible, shrink string table
777 static void checkSizes (lua_State *L, global_State *g) {
778 if (g->gckind != KGC_EMERGENCY) {
779 l_mem olddebt = g->GCdebt;
780 if (g->strt.nuse < g->strt.size / 4) /* string table too big? */
781 luaS_resize(L, g->strt.size / 2); /* shrink it a little */
782 g->GCestimate += g->GCdebt - olddebt; /* update estimate */
787 static GCObject *udata2finalize (global_State *g) {
788 GCObject *o = g->tobefnz; /* get first element */
789 lua_assert(tofinalize(o));
790 g->tobefnz = o->next; /* remove it from 'tobefnz' list */
791 o->next = g->allgc; /* return it to 'allgc' list */
793 resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */
795 makewhite(g, o); /* "sweep" object */
800 static void dothecall (lua_State *L, void *ud) {
802 luaD_callnoyield(L, L->top - 2, 0);
806 static void GCTM (lua_State *L, int propagateerrors) {
807 global_State *g = G(L);
810 setgcovalue(L, &v, udata2finalize(g));
811 tm = luaT_gettmbyobj(L, &v, TM_GC);
812 if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */
814 lu_byte oldah = L->allowhook;
815 int running = g->gcrunning;
816 L->allowhook = 0; /* stop debug hooks during GC metamethod */
817 g->gcrunning = 0; /* avoid GC steps */
818 setobj2s(L, L->top, tm); /* push finalizer... */
819 setobj2s(L, L->top + 1, &v); /* ... and its argument */
820 L->top += 2; /* and (next line) call the finalizer */
821 L->ci->callstatus |= CIST_FIN; /* will run a finalizer */
822 status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
823 L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */
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))
831 luaO_pushfstring(L, "error in __gc metamethod (%s)", msg);
832 status = LUA_ERRGCMM; /* error in __gc metamethod */
834 luaD_throw(L, status); /* re-throw error */
841 ** call a few (up to 'g->gcfinnum') finalizers
843 static int runafewfinalizers (lua_State *L) {
844 global_State *g = G(L);
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 */
856 ** call all pending finalizers
858 static void callallpendingfinalizers (lua_State *L) {
859 global_State *g = G(L);
866 ** find last 'next' field in list 'p' list (to add elements in its end)
868 static GCObject **findlast (GCObject **p) {
876 ** move all unreachable objects (or 'all' objects) that need
877 ** finalization from list 'finobj' to list 'tobefnz' (to be finalized)
879 static void separatetobefnz (global_State *g, int all) {
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 */
888 *p = curr->next; /* remove 'curr' from 'finobj' list */
889 curr->next = *lastnext; /* link at the end of 'tobefnz' list */
891 lastnext = &curr->next;
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.
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 */
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); /* change 'sweepgc' */
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 */
918 l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */
922 /* }====================================================== */
927 ** {======================================================
929 ** =======================================================
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).
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);
952 ** Enter first sweep phase.
953 ** The call to 'sweeplist' tries to make pointer point to an object
954 ** inside the list (instead of to the header), so that the real sweep do
955 ** not need to skip objects created between "now" and the start of the
958 static void entersweep (lua_State *L) {
959 global_State *g = G(L);
960 g->gcstate = GCSswpallgc;
961 lua_assert(g->sweepgc == NULL);
962 g->sweepgc = sweeplist(L, &g->allgc, 1);
966 void luaC_freeallobjects (lua_State *L) {
967 global_State *g = G(L);
968 separatetobefnz(g, 1); /* separate all objects with finalizers */
969 lua_assert(g->finobj == NULL);
970 callallpendingfinalizers(L);
971 lua_assert(g->tobefnz == NULL);
972 g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */
973 g->gckind = KGC_NORMAL;
974 sweepwholelist(L, &g->finobj);
975 sweepwholelist(L, &g->allgc);
976 sweepwholelist(L, &g->fixedgc); /* collect fixed objects */
977 lua_assert(g->strt.nuse == 0);
981 static l_mem atomic (lua_State *L) {
982 global_State *g = G(L);
984 GCObject *origweak, *origall;
985 GCObject *grayagain = g->grayagain; /* save original list */
986 lua_assert(g->ephemeron == NULL && g->weak == NULL);
987 lua_assert(!iswhite(g->mainthread));
988 g->gcstate = GCSinsideatomic;
989 g->GCmemtrav = 0; /* start counting work */
990 markobject(g, L); /* mark running thread */
991 /* registry and global metatables may be changed by API */
992 markvalue(g, &g->l_registry);
993 markmt(g); /* mark global metatables */
994 /* remark occasional upvalues of (maybe) dead threads */
996 propagateall(g); /* propagate changes */
997 work = g->GCmemtrav; /* stop counting (do not recount 'grayagain') */
999 propagateall(g); /* traverse 'grayagain' list */
1000 g->GCmemtrav = 0; /* restart counting */
1001 convergeephemerons(g);
1002 /* at this point, all strongly accessible objects are marked. */
1003 /* Clear values from weak tables, before checking finalizers */
1004 clearvalues(g, g->weak, NULL);
1005 clearvalues(g, g->allweak, NULL);
1006 origweak = g->weak; origall = g->allweak;
1007 work += g->GCmemtrav; /* stop counting (objects being finalized) */
1008 separatetobefnz(g, 0); /* separate objects to be finalized */
1009 g->gcfinnum = 1; /* there may be objects to be finalized */
1010 markbeingfnz(g); /* mark objects that will be finalized */
1011 propagateall(g); /* remark, to propagate 'resurrection' */
1012 g->GCmemtrav = 0; /* restart counting */
1013 convergeephemerons(g);
1014 /* at this point, all resurrected objects are marked. */
1015 /* remove dead objects from weak tables */
1016 clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */
1017 clearkeys(g, g->allweak, NULL); /* clear keys from all 'allweak' tables */
1018 /* clear values from resurrected weak tables */
1019 clearvalues(g, g->weak, origweak);
1020 clearvalues(g, g->allweak, origall);
1022 g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
1023 work += g->GCmemtrav; /* complete counting */
1024 return work; /* estimate of memory marked by 'atomic' */
1028 static lu_mem sweepstep (lua_State *L, global_State *g,
1029 int nextstate, GCObject **nextlist) {
1031 l_mem olddebt = g->GCdebt;
1032 g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
1033 g->GCestimate += g->GCdebt - olddebt; /* update estimate */
1034 if (g->sweepgc) /* is there still something to sweep? */
1035 return (GCSWEEPMAX * GCSWEEPCOST);
1037 /* else enter next state */
1038 g->gcstate = nextstate;
1039 g->sweepgc = nextlist;
1044 static lu_mem singlestep (lua_State *L) {
1045 global_State *g = G(L);
1046 switch (g->gcstate) {
1048 g->GCmemtrav = g->strt.size * sizeof(GCObject*);
1049 restartcollection(g);
1050 g->gcstate = GCSpropagate;
1051 return g->GCmemtrav;
1053 case GCSpropagate: {
1055 lua_assert(g->gray);
1057 if (g->gray == NULL) /* no more gray objects? */
1058 g->gcstate = GCSatomic; /* finish propagate phase */
1059 return g->GCmemtrav; /* memory traversed in this step */
1063 propagateall(g); /* make sure gray list is empty */
1064 work = atomic(L); /* work is what was traversed by 'atomic' */
1066 g->GCestimate = gettotalbytes(g); /* first estimate */;
1069 case GCSswpallgc: { /* sweep "regular" objects */
1070 return sweepstep(L, g, GCSswpfinobj, &g->finobj);
1072 case GCSswpfinobj: { /* sweep objects with finalizers */
1073 return sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
1075 case GCSswptobefnz: { /* sweep objects to be finalized */
1076 return sweepstep(L, g, GCSswpend, NULL);
1078 case GCSswpend: { /* finish sweeps */
1079 makewhite(g, g->mainthread); /* sweep main thread */
1081 g->gcstate = GCScallfin;
1084 case GCScallfin: { /* call remaining finalizers */
1085 if (g->tobefnz && g->gckind != KGC_EMERGENCY) {
1086 int n = runafewfinalizers(L);
1087 return (n * GCFINALIZECOST);
1089 else { /* emergency mode or no more finalizers */
1090 g->gcstate = GCSpause; /* finish collection */
1094 default: lua_assert(0); return 0;
1100 ** advances the garbage collector until it reaches a state allowed
1103 void luaC_runtilstate (lua_State *L, int statesmask) {
1104 global_State *g = G(L);
1105 while (!testbit(statesmask, g->gcstate))
1111 ** get GC debt and convert it from Kb to 'work units' (avoid zero debt
1114 static l_mem getdebt (global_State *g) {
1115 l_mem debt = g->GCdebt;
1116 int stepmul = g->gcstepmul;
1117 if (debt <= 0) return 0; /* minimal debt */
1119 debt = (debt / STEPMULADJ) + 1;
1120 debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM;
1126 ** performs a basic GC step when collector is running
1128 void luaC_step (lua_State *L) {
1129 global_State *g = G(L);
1130 l_mem debt = getdebt(g); /* GC deficit (be paid now) */
1131 if (!g->gcrunning) { /* not running? */
1132 luaE_setdebt(g, -GCSTEPSIZE * 10); /* avoid being called too often */
1135 do { /* repeat until pause or enough "credit" (negative debt) */
1136 lu_mem work = singlestep(L); /* perform one single step */
1138 } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);
1139 if (g->gcstate == GCSpause)
1140 setpause(g); /* pause until next cycle */
1142 debt = (debt / g->gcstepmul) * STEPMULADJ; /* convert 'work units' to Kb */
1143 luaE_setdebt(g, debt);
1144 runafewfinalizers(L);
1150 ** Performs a full GC cycle; if 'isemergency', set a flag to avoid
1151 ** some operations which could change the interpreter state in some
1152 ** unexpected ways (running finalizers and shrinking some structures).
1153 ** Before running the collection, check 'keepinvariant'; if it is true,
1154 ** there may be some objects marked as black, so the collector has
1155 ** to sweep all objects to turn them back to white (as white has not
1156 ** changed, nothing will be collected).
1158 void luaC_fullgc (lua_State *L, int isemergency) {
1159 global_State *g = G(L);
1160 lua_assert(g->gckind == KGC_NORMAL);
1161 if (isemergency) g->gckind = KGC_EMERGENCY; /* set flag */
1162 if (keepinvariant(g)) { /* black objects? */
1163 entersweep(L); /* sweep everything to turn them back to white */
1165 /* finish any pending sweep phase to start a new cycle */
1166 luaC_runtilstate(L, bitmask(GCSpause));
1167 luaC_runtilstate(L, ~bitmask(GCSpause)); /* start new collection */
1168 luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */
1169 /* estimate must be correct after a full GC cycle */
1170 lua_assert(g->GCestimate == gettotalbytes(g));
1171 luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */
1172 g->gckind = KGC_NORMAL;
1176 /* }====================================================== */