interplane.Get Omega
Read in your language

lua

[Ported from github.com/lua/lua] Cast in 'rl_readline_name'

Brought by drakestapleton

branch master Branches Tags History

lua / lgc.c

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