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);
214 white2gray(o); /* gray forever */
215 o->next = g->fixedgc;
224 /* }====================================================== */
229 ** {======================================================
231 ** =======================================================
236 ** mark an object. Userdata, strings, and closed upvalues are visited
237 ** and turned black here. Other objects are marked gray and added
238 ** to appropriate list to be visited (and turned black) later. (Open
239 ** upvalues are already linked in 'headuv' list.)
241 static void reallymarkobject (global_State *g, GCObject *o) {
247 g->GCmemtrav += sizelstring(gco2ts(o)->shrlen);
252 g->GCmemtrav += sizelstring(gco2ts(o)->u.lnglen);
255 case LUA_TUSERDATA: {
257 markobjectN(g, gco2u(o)->metatable); /* mark its metatable */
259 g->GCmemtrav += sizeudata(gco2u(o));
260 getuservalue(g->mainthread, gco2u(o), &uvalue);
261 if (valiswhite(&uvalue)) { /* markvalue(g, &uvalue); */
262 o = gcvalue(&uvalue);
268 linkgclist(gco2lcl(o), g->gray);
272 linkgclist(gco2ccl(o), g->gray);
276 linkgclist(gco2t(o), g->gray);
280 linkgclist(gco2th(o), g->gray);
284 linkgclist(gco2p(o), g->gray);
287 default: lua_assert(0); break;
293 ** mark metamethods for basic types
295 static void markmt (global_State *g) {
297 for (i=0; i < LUA_NUMTAGS; i++)
298 markobjectN(g, g->mt[i]);
303 ** mark all objects in list of being-finalized
305 static void markbeingfnz (global_State *g) {
307 for (o = g->tobefnz; o != NULL; o = o->next)
313 ** Mark all values stored in marked open upvalues from non-marked threads.
314 ** (Values from marked threads were already marked when traversing the
315 ** thread.) Remove from the list threads that no longer have upvalues and
316 ** not-marked threads.
318 static void remarkupvals (global_State *g) {
320 lua_State **p = &g->twups;
321 while ((thread = *p) != NULL) {
322 lua_assert(!isblack(thread)); /* threads are never black */
323 if (isgray(thread) && thread->openupval != NULL)
324 p = &thread->twups; /* keep marked thread with upvalues in the list */
325 else { /* thread is not marked or without upvalues */
327 *p = thread->twups; /* remove thread from the list */
328 thread->twups = thread; /* mark that it is out of list */
329 for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {
330 if (uv->u.open.touched) {
331 markvalue(g, uv->v); /* remark upvalue's value */
332 uv->u.open.touched = 0;
341 ** mark root set and reset all gray lists, to start a new collection
343 static void restartcollection (global_State *g) {
344 g->gray = g->grayagain = NULL;
345 g->weak = g->allweak = g->ephemeron = NULL;
346 markobject(g, g->mainthread);
347 markvalue(g, &g->l_registry);
349 markbeingfnz(g); /* mark any finalizing object left from previous cycle */
352 /* }====================================================== */
356 ** {======================================================
357 ** Traverse functions
358 ** =======================================================
362 ** Traverse a table with weak values and link it to proper list. During
363 ** propagate phase, keep it in 'grayagain' list, to be revisited in the
364 ** atomic phase. In the atomic phase, if table has any white value,
365 ** put it in 'weak' list, to be cleared.
367 static void traverseweakvalue (global_State *g, Table *h) {
368 Node *n, *limit = gnodelast(h);
369 /* if there is array part, assume it may have white values (it is not
370 worth traversing it now just to check) */
371 int hasclears = (h->sizearray > 0);
372 for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
374 if (ttisnil(gval(n))) /* entry is empty? */
375 removeentry(n); /* remove it */
377 lua_assert(!ttisnil(gkey(n)));
378 markvalue(g, gkey(n)); /* mark key */
379 if (!hasclears && iscleared(g, gval(n))) /* is there a white value? */
380 hasclears = 1; /* table will have to be cleared */
383 if (g->gcstate == GCSpropagate)
384 linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
386 linkgclist(h, g->weak); /* has to be cleared later */
391 ** Traverse an ephemeron table and link it to proper list. Returns true
392 ** iff any object was marked during this traversal (which implies that
393 ** convergence has to continue). During propagation phase, keep table
394 ** in 'grayagain' list, to be visited again in the atomic phase. In
395 ** the atomic phase, if table has any white->white entry, it has to
396 ** be revisited during ephemeron convergence (as that key may turn
397 ** black). Otherwise, if it has any white key, table has to be cleared
398 ** (in the atomic phase).
400 static int traverseephemeron (global_State *g, Table *h) {
401 int marked = 0; /* true if an object is marked in this traversal */
402 int hasclears = 0; /* true if table has white keys */
403 int hasww = 0; /* true if table has entry "white-key -> white-value" */
404 Node *n, *limit = gnodelast(h);
406 /* traverse array part */
407 for (i = 0; i < h->sizearray; i++) {
408 if (valiswhite(&h->array[i])) {
410 reallymarkobject(g, gcvalue(&h->array[i]));
413 /* traverse hash part */
414 for (n = gnode(h, 0); n < limit; n++) {
416 if (ttisnil(gval(n))) /* entry is empty? */
417 removeentry(n); /* remove it */
418 else if (iscleared(g, gkey(n))) { /* key is not marked (yet)? */
419 hasclears = 1; /* table must be cleared */
420 if (valiswhite(gval(n))) /* value not marked yet? */
421 hasww = 1; /* white-white entry */
423 else if (valiswhite(gval(n))) { /* value not marked yet? */
425 reallymarkobject(g, gcvalue(gval(n))); /* mark it now */
428 /* link table into proper list */
429 if (g->gcstate == GCSpropagate)
430 linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
431 else if (hasww) /* table has white->white entries? */
432 linkgclist(h, g->ephemeron); /* have to propagate again */
433 else if (hasclears) /* table has white keys? */
434 linkgclist(h, g->allweak); /* may have to clean white keys */
439 static void traversestrongtable (global_State *g, Table *h) {
440 Node *n, *limit = gnodelast(h);
442 for (i = 0; i < h->sizearray; i++) /* traverse array part */
443 markvalue(g, &h->array[i]);
444 for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
446 if (ttisnil(gval(n))) /* entry is empty? */
447 removeentry(n); /* remove it */
449 lua_assert(!ttisnil(gkey(n)));
450 markvalue(g, gkey(n)); /* mark key */
451 markvalue(g, gval(n)); /* mark value */
457 static lu_mem traversetable (global_State *g, Table *h) {
458 const char *weakkey, *weakvalue;
459 const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
460 markobjectN(g, h->metatable);
461 if (mode && ttisstring(mode) && /* is there a weak mode? */
462 ((weakkey = strchr(svalue(mode), 'k')),
463 (weakvalue = strchr(svalue(mode), 'v')),
464 (weakkey || weakvalue))) { /* is really weak? */
465 black2gray(h); /* keep table gray */
466 if (!weakkey) /* strong keys? */
467 traverseweakvalue(g, h);
468 else if (!weakvalue) /* strong values? */
469 traverseephemeron(g, h);
471 linkgclist(h, g->allweak); /* nothing to traverse now */
474 traversestrongtable(g, h);
475 return sizeof(Table) + sizeof(TValue) * h->sizearray +
476 sizeof(Node) * cast(size_t, allocsizenode(h));
481 ** Traverse a prototype. (While a prototype is being build, its
482 ** arrays can be larger than needed; the extra slots are filled with
483 ** NULL, so the use of 'markobjectN')
485 static int traverseproto (global_State *g, Proto *f) {
487 if (f->cache && iswhite(f->cache))
488 f->cache = NULL; /* allow cache to be collected */
489 markobjectN(g, f->source);
490 for (i = 0; i < f->sizek; i++) /* mark literals */
491 markvalue(g, &f->k[i]);
492 for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
493 markobjectN(g, f->upvalues[i].name);
494 for (i = 0; i < f->sizep; i++) /* mark nested protos */
495 markobjectN(g, f->p[i]);
496 for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
497 markobjectN(g, f->locvars[i].varname);
498 return sizeof(Proto) + sizeof(Instruction) * f->sizecode +
499 sizeof(Proto *) * f->sizep +
500 sizeof(TValue) * f->sizek +
501 sizeof(int) * f->sizelineinfo +
502 sizeof(LocVar) * f->sizelocvars +
503 sizeof(Upvaldesc) * f->sizeupvalues;
507 static lu_mem traverseCclosure (global_State *g, CClosure *cl) {
509 for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */
510 markvalue(g, &cl->upvalue[i]);
511 return sizeCclosure(cl->nupvalues);
515 ** open upvalues point to values in a thread, so those values should
516 ** be marked when the thread is traversed except in the atomic phase
517 ** (because then the value cannot be changed by the thread and the
518 ** thread may not be traversed again)
520 static lu_mem traverseLclosure (global_State *g, LClosure *cl) {
522 markobjectN(g, cl->p); /* mark its prototype */
523 for (i = 0; i < cl->nupvalues; i++) { /* mark its upvalues */
524 UpVal *uv = cl->upvals[i];
526 if (upisopen(uv) && g->gcstate != GCSinsideatomic)
527 uv->u.open.touched = 1; /* can be marked in 'remarkupvals' */
532 return sizeLclosure(cl->nupvalues);
536 static lu_mem traversethread (global_State *g, lua_State *th) {
539 return 1; /* stack not completely built yet */
540 lua_assert(g->gcstate == GCSinsideatomic ||
541 th->openupval == NULL || isintwups(th));
542 for (; o < th->top; o++) /* mark live elements in the stack */
544 if (g->gcstate == GCSinsideatomic) { /* final traversal? */
545 StkId lim = th->stack + th->stacksize; /* real end of stack */
546 for (; o < lim; o++) /* clear not-marked stack slice */
548 /* 'remarkupvals' may have removed thread from 'twups' list */
549 if (!isintwups(th) && th->openupval != NULL) {
550 th->twups = g->twups; /* link it back to the list */
554 else if (g->gckind != KGC_EMERGENCY)
555 luaD_shrinkstack(th); /* do not change stack in emergency cycle */
556 return (sizeof(lua_State) + sizeof(TValue) * th->stacksize +
557 sizeof(CallInfo) * th->nci);
562 ** traverse one gray object, turning it to black (except for threads,
563 ** which are always gray).
565 static void propagatemark (global_State *g) {
567 GCObject *o = g->gray;
568 lua_assert(isgray(o));
573 g->gray = h->gclist; /* remove from 'gray' list */
574 size = traversetable(g, h);
578 LClosure *cl = gco2lcl(o);
579 g->gray = cl->gclist; /* remove from 'gray' list */
580 size = traverseLclosure(g, cl);
584 CClosure *cl = gco2ccl(o);
585 g->gray = cl->gclist; /* remove from 'gray' list */
586 size = traverseCclosure(g, cl);
590 lua_State *th = gco2th(o);
591 g->gray = th->gclist; /* remove from 'gray' list */
592 linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
594 size = traversethread(g, th);
599 g->gray = p->gclist; /* remove from 'gray' list */
600 size = traverseproto(g, p);
603 default: lua_assert(0); return;
605 g->GCmemtrav += size;
609 static void propagateall (global_State *g) {
610 while (g->gray) propagatemark(g);
614 static void convergeephemerons (global_State *g) {
618 GCObject *next = g->ephemeron; /* get ephemeron list */
619 g->ephemeron = NULL; /* tables may return to this list when traversed */
621 while ((w = next) != NULL) {
622 next = gco2t(w)->gclist;
623 if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */
624 propagateall(g); /* propagate changes */
625 changed = 1; /* will have to revisit all ephemeron tables */
631 /* }====================================================== */
635 ** {======================================================
637 ** =======================================================
642 ** clear entries with unmarked keys from all weaktables in list 'l' up
645 static void clearkeys (global_State *g, GCObject *l, GCObject *f) {
646 for (; l != f; l = gco2t(l)->gclist) {
648 Node *n, *limit = gnodelast(h);
649 for (n = gnode(h, 0); n < limit; n++) {
650 if (!ttisnil(gval(n)) && (iscleared(g, gkey(n)))) {
651 setnilvalue(gval(n)); /* remove value ... */
652 removeentry(n); /* and remove entry from table */
660 ** clear entries with unmarked values from all weaktables in list 'l' up
663 static void clearvalues (global_State *g, GCObject *l, GCObject *f) {
664 for (; l != f; l = gco2t(l)->gclist) {
666 Node *n, *limit = gnodelast(h);
668 for (i = 0; i < h->sizearray; i++) {
669 TValue *o = &h->array[i];
670 if (iscleared(g, o)) /* value was collected? */
671 setnilvalue(o); /* remove value */
673 for (n = gnode(h, 0); n < limit; n++) {
674 if (!ttisnil(gval(n)) && iscleared(g, gval(n))) {
675 setnilvalue(gval(n)); /* remove value ... */
676 removeentry(n); /* and remove entry from table */
683 void luaC_upvdeccount (lua_State *L, UpVal *uv) {
684 lua_assert(uv->refcount > 0);
686 if (uv->refcount == 0 && !upisopen(uv))
691 static void freeLclosure (lua_State *L, LClosure *cl) {
693 for (i = 0; i < cl->nupvalues; i++) {
694 UpVal *uv = cl->upvals[i];
696 luaC_upvdeccount(L, uv);
698 luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
702 static void freeobj (lua_State *L, GCObject *o) {
704 case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
706 freeLclosure(L, gco2lcl(o));
710 luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));
713 case LUA_TTABLE: luaH_free(L, gco2t(o)); break;
714 case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
715 case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
717 luaS_remove(L, gco2ts(o)); /* remove it from hash table */
718 luaM_freemem(L, o, sizelstring(gco2ts(o)->shrlen));
721 luaM_freemem(L, o, sizelstring(gco2ts(o)->u.lnglen));
724 default: lua_assert(0);
729 #define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM)
730 static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);
734 ** sweep at most 'count' elements from a list of GCObjects erasing dead
735 ** objects, where a dead object is one marked with the old (non current)
736 ** white; change all non-dead objects back to white, preparing for next
737 ** collection cycle. Return where to continue the traversal or NULL if
740 static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
741 global_State *g = G(L);
742 int ow = otherwhite(g);
743 int white = luaC_white(g); /* current white */
744 while (*p != NULL && count-- > 0) {
746 int marked = curr->marked;
747 if (isdeadm(ow, marked)) { /* is 'curr' dead? */
748 *p = curr->next; /* remove 'curr' from list */
749 freeobj(L, curr); /* erase 'curr' */
751 else { /* change mark to 'white' */
752 curr->marked = cast_byte((marked & maskcolors) | white);
753 p = &curr->next; /* go to next element */
756 return (*p == NULL) ? NULL : p;
761 ** sweep a list until a live object (or end of list)
763 static GCObject **sweeptolive (lua_State *L, GCObject **p) {
766 p = sweeplist(L, p, 1);
771 /* }====================================================== */
775 ** {======================================================
777 ** =======================================================
781 ** If possible, shrink string table
783 static void checkSizes (lua_State *L, global_State *g) {
784 if (g->gckind != KGC_EMERGENCY) {
785 l_mem olddebt = g->GCdebt;
786 if (g->strt.nuse < g->strt.size / 4) /* string table too big? */
787 luaS_resize(L, g->strt.size / 2); /* shrink it a little */
788 g->GCestimate += g->GCdebt - olddebt; /* update estimate */
793 static GCObject *udata2finalize (global_State *g) {
794 GCObject *o = g->tobefnz; /* get first element */
795 lua_assert(tofinalize(o));
796 g->tobefnz = o->next; /* remove it from 'tobefnz' list */
797 o->next = g->allgc; /* return it to 'allgc' list */
799 resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */
801 makewhite(g, o); /* "sweep" object */
806 static void dothecall (lua_State *L, void *ud) {
808 luaD_callnoyield(L, L->top - 2, 0);
812 static void GCTM (lua_State *L, int propagateerrors) {
813 global_State *g = G(L);
816 setgcovalue(L, &v, udata2finalize(g));
817 tm = luaT_gettmbyobj(L, &v, TM_GC);
818 if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */
820 lu_byte oldah = L->allowhook;
821 int running = g->gcrunning;
822 L->allowhook = 0; /* stop debug hooks during GC metamethod */
823 g->gcrunning = 0; /* avoid GC steps */
824 setobj2s(L, L->top, tm); /* push finalizer... */
825 setobj2s(L, L->top + 1, &v); /* ... and its argument */
826 L->top += 2; /* and (next line) call the finalizer */
827 L->ci->callstatus |= CIST_FIN; /* will run a finalizer */
828 status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
829 L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */
830 L->allowhook = oldah; /* restore hooks */
831 g->gcrunning = running; /* restore state */
832 if (status != LUA_OK && propagateerrors) { /* error while running __gc? */
833 if (status == LUA_ERRRUN) { /* is there an error object? */
834 const char *msg = (ttisstring(L->top - 1))
837 luaO_pushfstring(L, "error in __gc metamethod (%s)", msg);
838 status = LUA_ERRGCMM; /* error in __gc metamethod */
840 luaD_throw(L, status); /* re-throw error */
847 ** call a few (up to 'g->gcfinnum') finalizers
849 static int runafewfinalizers (lua_State *L) {
850 global_State *g = G(L);
852 lua_assert(!g->tobefnz || g->gcfinnum > 0);
853 for (i = 0; g->tobefnz && i < g->gcfinnum; i++)
854 GCTM(L, 1); /* call one finalizer */
855 g->gcfinnum = (!g->tobefnz) ? 0 /* nothing more to finalize? */
856 : g->gcfinnum * 2; /* else call a few more next time */
862 ** call all pending finalizers
864 static void callallpendingfinalizers (lua_State *L) {
865 global_State *g = G(L);
872 ** find last 'next' field in list 'p' list (to add elements in its end)
874 static GCObject **findlast (GCObject **p) {
882 ** move all unreachable objects (or 'all' objects) that need
883 ** finalization from list 'finobj' to list 'tobefnz' (to be finalized)
885 static void separatetobefnz (global_State *g, int all) {
887 GCObject **p = &g->finobj;
888 GCObject **lastnext = findlast(&g->tobefnz);
889 while ((curr = *p) != NULL) { /* traverse all finalizable objects */
890 lua_assert(tofinalize(curr));
891 if (!(iswhite(curr) || all)) /* not being collected? */
892 p = &curr->next; /* don't bother with it */
894 *p = curr->next; /* remove 'curr' from 'finobj' list */
895 curr->next = *lastnext; /* link at the end of 'tobefnz' list */
897 lastnext = &curr->next;
904 ** if object 'o' has a finalizer, remove it from 'allgc' list (must
905 ** search the list to find it) and link it in 'finobj' list.
907 void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
908 global_State *g = G(L);
909 if (tofinalize(o) || /* obj. is already marked... */
910 gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */
911 return; /* nothing to be done */
912 else { /* move 'o' to 'finobj' list */
914 if (issweepphase(g)) {
915 makewhite(g, o); /* "sweep" object 'o' */
916 if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */
917 g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */
919 /* search for pointer pointing to 'o' */
920 for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
921 *p = o->next; /* remove 'o' from 'allgc' list */
922 o->next = g->finobj; /* link it in 'finobj' list */
924 l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */
928 /* }====================================================== */
933 ** {======================================================
935 ** =======================================================
940 ** Set a reasonable "time" to wait before starting a new GC cycle; cycle
941 ** will start when memory use hits threshold. (Division by 'estimate'
942 ** should be OK: it cannot be zero (because Lua cannot even start with
943 ** less than PAUSEADJ bytes).
945 static void setpause (global_State *g) {
946 l_mem threshold, debt;
947 l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */
948 lua_assert(estimate > 0);
949 threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */
950 ? estimate * g->gcpause /* no overflow */
951 : MAX_LMEM; /* overflow; truncate to maximum */
952 debt = gettotalbytes(g) - threshold;
953 luaE_setdebt(g, debt);
958 ** Enter first sweep phase.
959 ** The call to 'sweeplist' tries to make pointer point to an object
960 ** inside the list (instead of to the header), so that the real sweep do
961 ** not need to skip objects created between "now" and the start of the
964 static void entersweep (lua_State *L) {
965 global_State *g = G(L);
966 g->gcstate = GCSswpallgc;
967 lua_assert(g->sweepgc == NULL);
968 g->sweepgc = sweeplist(L, &g->allgc, 1);
972 void luaC_freeallobjects (lua_State *L) {
973 global_State *g = G(L);
974 separatetobefnz(g, 1); /* separate all objects with finalizers */
975 lua_assert(g->finobj == NULL);
976 callallpendingfinalizers(L);
977 lua_assert(g->tobefnz == NULL);
978 g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */
979 g->gckind = KGC_NORMAL;
980 sweepwholelist(L, &g->finobj);
981 sweepwholelist(L, &g->allgc);
982 sweepwholelist(L, &g->fixedgc); /* collect fixed objects */
983 lua_assert(g->strt.nuse == 0);
987 static l_mem atomic (lua_State *L) {
988 global_State *g = G(L);
990 GCObject *origweak, *origall;
991 GCObject *grayagain = g->grayagain; /* save original list */
992 lua_assert(g->ephemeron == NULL && g->weak == NULL);
993 lua_assert(!iswhite(g->mainthread));
994 g->gcstate = GCSinsideatomic;
995 g->GCmemtrav = 0; /* start counting work */
996 markobject(g, L); /* mark running thread */
997 /* registry and global metatables may be changed by API */
998 markvalue(g, &g->l_registry);
999 markmt(g); /* mark global metatables */
1000 /* remark occasional upvalues of (maybe) dead threads */
1002 propagateall(g); /* propagate changes */
1003 work = g->GCmemtrav; /* stop counting (do not recount 'grayagain') */
1004 g->gray = grayagain;
1005 propagateall(g); /* traverse 'grayagain' list */
1006 g->GCmemtrav = 0; /* restart counting */
1007 convergeephemerons(g);
1008 /* at this point, all strongly accessible objects are marked. */
1009 /* Clear values from weak tables, before checking finalizers */
1010 clearvalues(g, g->weak, NULL);
1011 clearvalues(g, g->allweak, NULL);
1012 origweak = g->weak; origall = g->allweak;
1013 work += g->GCmemtrav; /* stop counting (objects being finalized) */
1014 separatetobefnz(g, 0); /* separate objects to be finalized */
1015 g->gcfinnum = 1; /* there may be objects to be finalized */
1016 markbeingfnz(g); /* mark objects that will be finalized */
1017 propagateall(g); /* remark, to propagate 'resurrection' */
1018 g->GCmemtrav = 0; /* restart counting */
1019 convergeephemerons(g);
1020 /* at this point, all resurrected objects are marked. */
1021 /* remove dead objects from weak tables */
1022 clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */
1023 clearkeys(g, g->allweak, NULL); /* clear keys from all 'allweak' tables */
1024 /* clear values from resurrected weak tables */
1025 clearvalues(g, g->weak, origweak);
1026 clearvalues(g, g->allweak, origall);
1028 g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
1029 work += g->GCmemtrav; /* complete counting */
1030 return work; /* estimate of memory marked by 'atomic' */
1034 static lu_mem sweepstep (lua_State *L, global_State *g,
1035 int nextstate, GCObject **nextlist) {
1037 l_mem olddebt = g->GCdebt;
1038 g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
1039 g->GCestimate += g->GCdebt - olddebt; /* update estimate */
1040 if (g->sweepgc) /* is there still something to sweep? */
1041 return (GCSWEEPMAX * GCSWEEPCOST);
1043 /* else enter next state */
1044 g->gcstate = nextstate;
1045 g->sweepgc = nextlist;
1050 static lu_mem singlestep (lua_State *L) {
1051 global_State *g = G(L);
1052 switch (g->gcstate) {
1054 g->GCmemtrav = g->strt.size * sizeof(GCObject*);
1055 restartcollection(g);
1056 g->gcstate = GCSpropagate;
1057 return g->GCmemtrav;
1059 case GCSpropagate: {
1061 lua_assert(g->gray);
1063 if (g->gray == NULL) /* no more gray objects? */
1064 g->gcstate = GCSatomic; /* finish propagate phase */
1065 return g->GCmemtrav; /* memory traversed in this step */
1069 propagateall(g); /* make sure gray list is empty */
1070 work = atomic(L); /* work is what was traversed by 'atomic' */
1072 g->GCestimate = gettotalbytes(g); /* first estimate */;
1075 case GCSswpallgc: { /* sweep "regular" objects */
1076 return sweepstep(L, g, GCSswpfinobj, &g->finobj);
1078 case GCSswpfinobj: { /* sweep objects with finalizers */
1079 return sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
1081 case GCSswptobefnz: { /* sweep objects to be finalized */
1082 return sweepstep(L, g, GCSswpend, NULL);
1084 case GCSswpend: { /* finish sweeps */
1085 makewhite(g, g->mainthread); /* sweep main thread */
1087 g->gcstate = GCScallfin;
1090 case GCScallfin: { /* call remaining finalizers */
1091 if (g->tobefnz && g->gckind != KGC_EMERGENCY) {
1092 int n = runafewfinalizers(L);
1093 return (n * GCFINALIZECOST);
1095 else { /* emergency mode or no more finalizers */
1096 g->gcstate = GCSpause; /* finish collection */
1100 default: lua_assert(0); return 0;
1106 ** advances the garbage collector until it reaches a state allowed
1109 void luaC_runtilstate (lua_State *L, int statesmask) {
1110 global_State *g = G(L);
1111 while (!testbit(statesmask, g->gcstate))
1117 ** get GC debt and convert it from Kb to 'work units' (avoid zero debt
1120 static l_mem getdebt (global_State *g) {
1121 l_mem debt = g->GCdebt;
1122 int stepmul = g->gcstepmul;
1123 if (debt <= 0) return 0; /* minimal debt */
1125 debt = (debt / STEPMULADJ) + 1;
1126 debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM;
1132 ** performs a basic GC step when collector is running
1134 void luaC_step (lua_State *L) {
1135 global_State *g = G(L);
1136 l_mem debt = getdebt(g); /* GC deficit (be paid now) */
1137 if (!g->gcrunning) { /* not running? */
1138 luaE_setdebt(g, -GCSTEPSIZE * 10); /* avoid being called too often */
1141 do { /* repeat until pause or enough "credit" (negative debt) */
1142 lu_mem work = singlestep(L); /* perform one single step */
1144 } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);
1145 if (g->gcstate == GCSpause)
1146 setpause(g); /* pause until next cycle */
1148 debt = (debt / g->gcstepmul) * STEPMULADJ; /* convert 'work units' to Kb */
1149 luaE_setdebt(g, debt);
1150 runafewfinalizers(L);
1156 ** Performs a full GC cycle; if 'isemergency', set a flag to avoid
1157 ** some operations which could change the interpreter state in some
1158 ** unexpected ways (running finalizers and shrinking some structures).
1159 ** Before running the collection, check 'keepinvariant'; if it is true,
1160 ** there may be some objects marked as black, so the collector has
1161 ** to sweep all objects to turn them back to white (as white has not
1162 ** changed, nothing will be collected).
1164 void luaC_fullgc (lua_State *L, int isemergency) {
1165 global_State *g = G(L);
1166 lua_assert(g->gckind == KGC_NORMAL);
1167 if (isemergency) g->gckind = KGC_EMERGENCY; /* set flag */
1168 if (keepinvariant(g)) { /* black objects? */
1169 entersweep(L); /* sweep everything to turn them back to white */
1171 /* finish any pending sweep phase to start a new cycle */
1172 luaC_runtilstate(L, bitmask(GCSpause));
1173 luaC_runtilstate(L, ~bitmask(GCSpause)); /* start new collection */
1174 luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */
1175 /* estimate must be correct after a full GC cycle */
1176 lua_assert(g->GCestimate == gettotalbytes(g));
1177 luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */
1178 g->gckind = KGC_NORMAL;
1182 /* }====================================================== */
1184 LUA_API void lua_mlock (lua_State *L, int en) {
1185 global_State *g = G(L);