1 /*
2 ** $Id: lgc.c,v 2.215.1.2 2017/08/31 16:15:27 roberto Exp $
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
13 #include <string.h>
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 ** internal state for collector while inside the atomic phase. The
31 ** collector should never be in this state while running regular code.
32 */
33 #define GCSinsideatomic (GCSpause + 1)
34
35 /*
36 ** cost of sweeping one element (the size of a small object divided
37 ** by some adjust for the sweep speed)
38 */
39 #define GCSWEEPCOST ((sizeof(TString) + 4) / 4)
40
41 /* maximum number of elements to sweep in each single step */
42 #define GCSWEEPMAX (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4))
43
44 /* cost of calling one finalizer */
45 #define GCFINALIZECOST GCSWEEPCOST
46
47
48 /*
49 ** macro to adjust 'stepmul': 'stepmul' is actually used like
50 ** 'stepmul / STEPMULADJ' (value chosen by tests)
51 */
52 #define STEPMULADJ 200
53
54
55 /*
56 ** macro to adjust 'pause': 'pause' is actually used like
57 ** 'pause / PAUSEADJ' (value chosen by tests)
58 */
59 #define PAUSEADJ 100
60
61
62 /*
63 ** 'makewhite' erases all color bits then sets only the current white
64 ** bit
65 */
66 #define maskcolors (~(bitmask(BLACKBIT) | WHITEBITS))
67 #define makewhite(g,x) \
68 (x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g)))
69
70 #define white2gray(x) resetbits(x->marked, WHITEBITS)
71 #define black2gray(x) resetbit(x->marked, BLACKBIT)
72
73
74 #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
75
76 #define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))
77
78
79 #define checkconsistency(obj) \
80 lua_longassert(!iscollectable(obj) || righttt(obj))
81
82
83 #define markvalue(g,o) { checkconsistency(o); \
84 if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
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 static void reallymarkobject (global_State *g, GCObject *o);
95
96
97 /*
98 ** {======================================================
99 ** Generic functions
100 ** =======================================================
101 */
102
103
104 /*
105 ** one after last element in a hash array
106 */
107 #define gnodelast(h) gnode(h, cast(size_t, sizenode(h)))
108
109
110 /*
111 ** link collectable object 'o' into list pointed by 'p'
112 */
113 #define linkgclist(o,p) ((o)->gclist = (p), (p) = obj2gco(o))
114
115
116 /*
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
123 ** empty.
124 */
removeentry(Node * n)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 */
129 }
130
131
132 /*
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
138 */
iscleared(global_State * g,const TValue * o)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 */
143 return 0;
144 }
145 else return iswhite(gcvalue(o));
146 }
147
148
149 /*
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
153 ** same object.)
154 */
luaC_barrier_(lua_State * L,GCObject * o,GCObject * v)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 */
163 }
164 }
165
166
167 /*
168 ** barrier that moves collector backward, that is, mark the black object
169 ** pointing to a white object as gray again.
170 */
luaC_barrierback_(lua_State * L,Table * t)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);
176 }
177
178
179 /*
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
183 ** must be marked.
184 */
luaC_upvalbarrier_(lua_State * L,UpVal * uv)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))
190 markobject(g, o);
191 }
192
193
luaC_fix(lua_State * L,GCObject * o)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 */
200 g->fixedgc = o;
201 }
202
203
204 /*
205 ** create a new collectable object (with given type and size) and link
206 ** it to 'allgc' list.
207 */
luaC_newobj(lua_State * L,int tt,size_t sz)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);
212 o->tt = tt;
213 if (g->gcmlock) {
214 white2gray(o); /* gray forever */
215 o->next = g->fixedgc;
216 g->fixedgc = o;
217 } else {
218 o->next = g->allgc;
219 g->allgc = o;
220 }
221 return o;
222 }
223
224 /* }====================================================== */
225
226
227
228 /*
229 ** {======================================================
230 ** Mark functions
231 ** =======================================================
232 */
233
234
235 /*
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.)
240 */
reallymarkobject(global_State * g,GCObject * o)241 static void reallymarkobject (global_State *g, GCObject *o) {
242 reentry:
243 white2gray(o);
244 switch (o->tt) {
245 case LUA_TSHRSTR: {
246 gray2black(o);
247 g->GCmemtrav += sizelstring(gco2ts(o)->shrlen);
248 break;
249 }
250 case LUA_TLNGSTR: {
251 gray2black(o);
252 g->GCmemtrav += sizelstring(gco2ts(o)->u.lnglen);
253 break;
254 }
255 case LUA_TUSERDATA: {
256 TValue uvalue;
257 markobjectN(g, gco2u(o)->metatable); /* mark its metatable */
258 gray2black(o);
259 g->GCmemtrav += sizeudata(gco2u(o));
260 getuservalue(g->mainthread, gco2u(o), &uvalue);
261 if (valiswhite(&uvalue)) { /* markvalue(g, &uvalue); */
262 o = gcvalue(&uvalue);
263 goto reentry;
264 }
265 break;
266 }
267 case LUA_TLCL: {
268 linkgclist(gco2lcl(o), g->gray);
269 break;
270 }
271 case LUA_TCCL: {
272 linkgclist(gco2ccl(o), g->gray);
273 break;
274 }
275 case LUA_TTABLE: {
276 linkgclist(gco2t(o), g->gray);
277 break;
278 }
279 case LUA_TTHREAD: {
280 linkgclist(gco2th(o), g->gray);
281 break;
282 }
283 case LUA_TPROTO: {
284 linkgclist(gco2p(o), g->gray);
285 break;
286 }
287 default: lua_assert(0); break;
288 }
289 }
290
291
292 /*
293 ** mark metamethods for basic types
294 */
markmt(global_State * g)295 static void markmt (global_State *g) {
296 int i;
297 for (i=0; i < LUA_NUMTAGS; i++)
298 markobjectN(g, g->mt[i]);
299 }
300
301
302 /*
303 ** mark all objects in list of being-finalized
304 */
markbeingfnz(global_State * g)305 static void markbeingfnz (global_State *g) {
306 GCObject *o;
307 for (o = g->tobefnz; o != NULL; o = o->next)
308 markobject(g, o);
309 }
310
311
312 /*
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.
317 */
remarkupvals(global_State * g)318 static void remarkupvals (global_State *g) {
319 lua_State *thread;
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 */
326 UpVal *uv;
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;
333 }
334 }
335 }
336 }
337 }
338
339
340 /*
341 ** mark root set and reset all gray lists, to start a new collection
342 */
restartcollection(global_State * g)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);
348 markmt(g);
349 markbeingfnz(g); /* mark any finalizing object left from previous cycle */
350 }
351
352 /* }====================================================== */
353
354
355 /*
356 ** {======================================================
357 ** Traverse functions
358 ** =======================================================
359 */
360
361 /*
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.
366 */
traverseweakvalue(global_State * g,Table * h)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 */
373 checkdeadkey(n);
374 if (ttisnil(gval(n))) /* entry is empty? */
375 removeentry(n); /* remove it */
376 else {
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 */
381 }
382 }
383 if (g->gcstate == GCSpropagate)
384 linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
385 else if (hasclears)
386 linkgclist(h, g->weak); /* has to be cleared later */
387 }
388
389
390 /*
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).
399 */
traverseephemeron(global_State * g,Table * h)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);
405 unsigned int i;
406 /* traverse array part */
407 for (i = 0; i < h->sizearray; i++) {
408 if (valiswhite(&h->array[i])) {
409 marked = 1;
410 reallymarkobject(g, gcvalue(&h->array[i]));
411 }
412 }
413 /* traverse hash part */
414 for (n = gnode(h, 0); n < limit; n++) {
415 checkdeadkey(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 */
422 }
423 else if (valiswhite(gval(n))) { /* value not marked yet? */
424 marked = 1;
425 reallymarkobject(g, gcvalue(gval(n))); /* mark it now */
426 }
427 }
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 */
435 return marked;
436 }
437
438
traversestrongtable(global_State * g,Table * h)439 static void traversestrongtable (global_State *g, Table *h) {
440 Node *n, *limit = gnodelast(h);
441 unsigned int i;
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 */
445 checkdeadkey(n);
446 if (ttisnil(gval(n))) /* entry is empty? */
447 removeentry(n); /* remove it */
448 else {
449 lua_assert(!ttisnil(gkey(n)));
450 markvalue(g, gkey(n)); /* mark key */
451 markvalue(g, gval(n)); /* mark value */
452 }
453 }
454 }
455
456
traversetable(global_State * g,Table * h)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);
470 else /* all weak */
471 linkgclist(h, g->allweak); /* nothing to traverse now */
472 }
473 else /* not weak */
474 traversestrongtable(g, h);
475 return sizeof(Table) + sizeof(TValue) * h->sizearray +
476 sizeof(Node) * cast(size_t, allocsizenode(h));
477 }
478
479
480 /*
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')
484 */
traverseproto(global_State * g,Proto * f)485 static int traverseproto (global_State *g, Proto *f) {
486 int i;
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;
504 }
505
506
traverseCclosure(global_State * g,CClosure * cl)507 static lu_mem traverseCclosure (global_State *g, CClosure *cl) {
508 int i;
509 for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */
510 markvalue(g, &cl->upvalue[i]);
511 return sizeCclosure(cl->nupvalues);
512 }
513
514 /*
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)
519 */
traverseLclosure(global_State * g,LClosure * cl)520 static lu_mem traverseLclosure (global_State *g, LClosure *cl) {
521 int i;
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];
525 if (uv != NULL) {
526 if (upisopen(uv) && g->gcstate != GCSinsideatomic)
527 uv->u.open.touched = 1; /* can be marked in 'remarkupvals' */
528 else
529 markvalue(g, uv->v);
530 }
531 }
532 return sizeLclosure(cl->nupvalues);
533 }
534
535
traversethread(global_State * g,lua_State * th)536 static lu_mem traversethread (global_State *g, lua_State *th) {
537 StkId o = th->stack;
538 if (o == NULL)
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 */
543 markvalue(g, o);
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 */
547 setnilvalue(o);
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 */
551 g->twups = th;
552 }
553 }
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);
558 }
559
560
561 /*
562 ** traverse one gray object, turning it to black (except for threads,
563 ** which are always gray).
564 */
propagatemark(global_State * g)565 static void propagatemark (global_State *g) {
566 lu_mem size;
567 GCObject *o = g->gray;
568 lua_assert(isgray(o));
569 gray2black(o);
570 switch (o->tt) {
571 case LUA_TTABLE: {
572 Table *h = gco2t(o);
573 g->gray = h->gclist; /* remove from 'gray' list */
574 size = traversetable(g, h);
575 break;
576 }
577 case LUA_TLCL: {
578 LClosure *cl = gco2lcl(o);
579 g->gray = cl->gclist; /* remove from 'gray' list */
580 size = traverseLclosure(g, cl);
581 break;
582 }
583 case LUA_TCCL: {
584 CClosure *cl = gco2ccl(o);
585 g->gray = cl->gclist; /* remove from 'gray' list */
586 size = traverseCclosure(g, cl);
587 break;
588 }
589 case LUA_TTHREAD: {
590 lua_State *th = gco2th(o);
591 g->gray = th->gclist; /* remove from 'gray' list */
592 linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
593 black2gray(o);
594 size = traversethread(g, th);
595 break;
596 }
597 case LUA_TPROTO: {
598 Proto *p = gco2p(o);
599 g->gray = p->gclist; /* remove from 'gray' list */
600 size = traverseproto(g, p);
601 break;
602 }
603 default: lua_assert(0); return;
604 }
605 g->GCmemtrav += size;
606 }
607
608
propagateall(global_State * g)609 static void propagateall (global_State *g) {
610 while (g->gray) propagatemark(g);
611 }
612
613
convergeephemerons(global_State * g)614 static void convergeephemerons (global_State *g) {
615 int changed;
616 do {
617 GCObject *w;
618 GCObject *next = g->ephemeron; /* get ephemeron list */
619 g->ephemeron = NULL; /* tables may return to this list when traversed */
620 changed = 0;
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 */
626 }
627 }
628 } while (changed);
629 }
630
631 /* }====================================================== */
632
633
634 /*
635 ** {======================================================
636 ** Sweep Functions
637 ** =======================================================
638 */
639
640
641 /*
642 ** clear entries with unmarked keys from all weaktables in list 'l' up
643 ** to element 'f'
644 */
clearkeys(global_State * g,GCObject * l,GCObject * f)645 static void clearkeys (global_State *g, GCObject *l, GCObject *f) {
646 for (; l != f; l = gco2t(l)->gclist) {
647 Table *h = gco2t(l);
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 }
653 if (ttisnil(gval(n))) /* is entry empty? */
654 removeentry(n); /* remove entry from table */
655 }
656 }
657 }
658
659
660 /*
661 ** clear entries with unmarked values from all weaktables in list 'l' up
662 ** to element 'f'
663 */
clearvalues(global_State * g,GCObject * l,GCObject * f)664 static void clearvalues (global_State *g, GCObject *l, GCObject *f) {
665 for (; l != f; l = gco2t(l)->gclist) {
666 Table *h = gco2t(l);
667 Node *n, *limit = gnodelast(h);
668 unsigned int i;
669 for (i = 0; i < h->sizearray; i++) {
670 TValue *o = &h->array[i];
671 if (iscleared(g, o)) /* value was collected? */
672 setnilvalue(o); /* remove value */
673 }
674 for (n = gnode(h, 0); n < limit; n++) {
675 if (!ttisnil(gval(n)) && iscleared(g, gval(n))) {
676 setnilvalue(gval(n)); /* remove value ... */
677 removeentry(n); /* and remove entry from table */
678 }
679 }
680 }
681 }
682
683
luaC_upvdeccount(lua_State * L,UpVal * uv)684 void luaC_upvdeccount (lua_State *L, UpVal *uv) {
685 lua_assert(uv->refcount > 0);
686 uv->refcount--;
687 if (uv->refcount == 0 && !upisopen(uv))
688 luaM_free(L, uv);
689 }
690
691
freeLclosure(lua_State * L,LClosure * cl)692 static void freeLclosure (lua_State *L, LClosure *cl) {
693 int i;
694 for (i = 0; i < cl->nupvalues; i++) {
695 UpVal *uv = cl->upvals[i];
696 if (uv)
697 luaC_upvdeccount(L, uv);
698 }
699 luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
700 }
701
702
freeobj(lua_State * L,GCObject * o)703 static void freeobj (lua_State *L, GCObject *o) {
704 switch (o->tt) {
705 case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
706 case LUA_TLCL: {
707 freeLclosure(L, gco2lcl(o));
708 break;
709 }
710 case LUA_TCCL: {
711 luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));
712 break;
713 }
714 case LUA_TTABLE: luaH_free(L, gco2t(o)); break;
715 case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
716 case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
717 case LUA_TSHRSTR:
718 luaS_remove(L, gco2ts(o)); /* remove it from hash table */
719 luaM_freemem(L, o, sizelstring(gco2ts(o)->shrlen));
720 break;
721 case LUA_TLNGSTR: {
722 luaM_freemem(L, o, sizelstring(gco2ts(o)->u.lnglen));
723 break;
724 }
725 default: lua_assert(0);
726 }
727 }
728
729
730 #define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM)
731 static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);
732
733
734 /*
735 ** sweep at most 'count' elements from a list of GCObjects erasing dead
736 ** objects, where a dead object is one marked with the old (non current)
737 ** white; change all non-dead objects back to white, preparing for next
738 ** collection cycle. Return where to continue the traversal or NULL if
739 ** list is finished.
740 */
sweeplist(lua_State * L,GCObject ** p,lu_mem count)741 static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
742 global_State *g = G(L);
743 int ow = otherwhite(g);
744 int white = luaC_white(g); /* current white */
745 while (*p != NULL && count-- > 0) {
746 GCObject *curr = *p;
747 int marked = curr->marked;
748 if (isdeadm(ow, marked)) { /* is 'curr' dead? */
749 *p = curr->next; /* remove 'curr' from list */
750 freeobj(L, curr); /* erase 'curr' */
751 }
752 else { /* change mark to 'white' */
753 curr->marked = cast_byte((marked & maskcolors) | white);
754 p = &curr->next; /* go to next element */
755 }
756 }
757 return (*p == NULL) ? NULL : p;
758 }
759
760
761 /*
762 ** sweep a list until a live object (or end of list)
763 */
sweeptolive(lua_State * L,GCObject ** p)764 static GCObject **sweeptolive (lua_State *L, GCObject **p) {
765 GCObject **old = p;
766 do {
767 p = sweeplist(L, p, 1);
768 } while (p == old);
769 return p;
770 }
771
772 /* }====================================================== */
773
774
775 /*
776 ** {======================================================
777 ** Finalization
778 ** =======================================================
779 */
780
781 /*
782 ** If possible, shrink string table
783 */
checkSizes(lua_State * L,global_State * g)784 static void checkSizes (lua_State *L, global_State *g) {
785 if (g->gckind != KGC_EMERGENCY) {
786 l_mem olddebt = g->GCdebt;
787 if (g->strt.nuse < g->strt.size / 4) /* string table too big? */
788 luaS_resize(L, g->strt.size / 2); /* shrink it a little */
789 g->GCestimate += g->GCdebt - olddebt; /* update estimate */
790 }
791 }
792
793
udata2finalize(global_State * g)794 static GCObject *udata2finalize (global_State *g) {
795 GCObject *o = g->tobefnz; /* get first element */
796 lua_assert(tofinalize(o));
797 g->tobefnz = o->next; /* remove it from 'tobefnz' list */
798 o->next = g->allgc; /* return it to 'allgc' list */
799 g->allgc = o;
800 resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */
801 if (issweepphase(g))
802 makewhite(g, o); /* "sweep" object */
803 return o;
804 }
805
806
dothecall(lua_State * L,void * ud)807 static void dothecall (lua_State *L, void *ud) {
808 UNUSED(ud);
809 luaD_callnoyield(L, L->top - 2, 0);
810 }
811
812
GCTM(lua_State * L,int propagateerrors)813 static void GCTM (lua_State *L, int propagateerrors) {
814 global_State *g = G(L);
815 const TValue *tm;
816 TValue v;
817 setgcovalue(L, &v, udata2finalize(g));
818 tm = luaT_gettmbyobj(L, &v, TM_GC);
819 if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */
820 int status;
821 lu_byte oldah = L->allowhook;
822 int running = g->gcrunning;
823 L->allowhook = 0; /* stop debug hooks during GC metamethod */
824 g->gcrunning = 0; /* avoid GC steps */
825 setobj2s(L, L->top, tm); /* push finalizer... */
826 setobj2s(L, L->top + 1, &v); /* ... and its argument */
827 L->top += 2; /* and (next line) call the finalizer */
828 L->ci->callstatus |= CIST_FIN; /* will run a finalizer */
829 status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
830 L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */
831 L->allowhook = oldah; /* restore hooks */
832 g->gcrunning = running; /* restore state */
833 if (status != LUA_OK && propagateerrors) { /* error while running __gc? */
834 if (status == LUA_ERRRUN) { /* is there an error object? */
835 const char *msg = (ttisstring(L->top - 1))
836 ? svalue(L->top - 1)
837 : "no message";
838 luaO_pushfstring(L, "error in __gc metamethod (%s)", msg);
839 status = LUA_ERRGCMM; /* error in __gc metamethod */
840 }
841 luaD_throw(L, status); /* re-throw error */
842 }
843 }
844 }
845
846
847 /*
848 ** call a few (up to 'g->gcfinnum') finalizers
849 */
runafewfinalizers(lua_State * L)850 static int runafewfinalizers (lua_State *L) {
851 global_State *g = G(L);
852 unsigned int i;
853 lua_assert(!g->tobefnz || g->gcfinnum > 0);
854 for (i = 0; g->tobefnz && i < g->gcfinnum; i++)
855 GCTM(L, 1); /* call one finalizer */
856 g->gcfinnum = (!g->tobefnz) ? 0 /* nothing more to finalize? */
857 : g->gcfinnum * 2; /* else call a few more next time */
858 return i;
859 }
860
861
862 /*
863 ** call all pending finalizers
864 */
callallpendingfinalizers(lua_State * L)865 static void callallpendingfinalizers (lua_State *L) {
866 global_State *g = G(L);
867 while (g->tobefnz)
868 GCTM(L, 0);
869 }
870
871
872 /*
873 ** find last 'next' field in list 'p' list (to add elements in its end)
874 */
findlast(GCObject ** p)875 static GCObject **findlast (GCObject **p) {
876 while (*p != NULL)
877 p = &(*p)->next;
878 return p;
879 }
880
881
882 /*
883 ** move all unreachable objects (or 'all' objects) that need
884 ** finalization from list 'finobj' to list 'tobefnz' (to be finalized)
885 */
separatetobefnz(global_State * g,int all)886 static void separatetobefnz (global_State *g, int all) {
887 GCObject *curr;
888 GCObject **p = &g->finobj;
889 GCObject **lastnext = findlast(&g->tobefnz);
890 while ((curr = *p) != NULL) { /* traverse all finalizable objects */
891 lua_assert(tofinalize(curr));
892 if (!(iswhite(curr) || all)) /* not being collected? */
893 p = &curr->next; /* don't bother with it */
894 else {
895 *p = curr->next; /* remove 'curr' from 'finobj' list */
896 curr->next = *lastnext; /* link at the end of 'tobefnz' list */
897 *lastnext = curr;
898 lastnext = &curr->next;
899 }
900 }
901 }
902
903
904 /*
905 ** if object 'o' has a finalizer, remove it from 'allgc' list (must
906 ** search the list to find it) and link it in 'finobj' list.
907 */
luaC_checkfinalizer(lua_State * L,GCObject * o,Table * mt)908 void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
909 global_State *g = G(L);
910 if (tofinalize(o) || /* obj. is already marked... */
911 gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */
912 return; /* nothing to be done */
913 else { /* move 'o' to 'finobj' list */
914 GCObject **p;
915 if (issweepphase(g)) {
916 makewhite(g, o); /* "sweep" object 'o' */
917 if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */
918 g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */
919 }
920 /* search for pointer pointing to 'o' */
921 for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
922 *p = o->next; /* remove 'o' from 'allgc' list */
923 o->next = g->finobj; /* link it in 'finobj' list */
924 g->finobj = o;
925 l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */
926 }
927 }
928
929 /* }====================================================== */
930
931
932
933 /*
934 ** {======================================================
935 ** GC control
936 ** =======================================================
937 */
938
939
940 /*
941 ** Set a reasonable "time" to wait before starting a new GC cycle; cycle
942 ** will start when memory use hits threshold. (Division by 'estimate'
943 ** should be OK: it cannot be zero (because Lua cannot even start with
944 ** less than PAUSEADJ bytes).
945 */
setpause(global_State * g)946 static void setpause (global_State *g) {
947 l_mem threshold, debt;
948 l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */
949 lua_assert(estimate > 0);
950 threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */
951 ? estimate * g->gcpause /* no overflow */
952 : MAX_LMEM; /* overflow; truncate to maximum */
953 debt = gettotalbytes(g) - threshold;
954 luaE_setdebt(g, debt);
955 }
956
957
958 /*
959 ** Enter first sweep phase.
960 ** The call to 'sweeplist' tries to make pointer point to an object
961 ** inside the list (instead of to the header), so that the real sweep do
962 ** not need to skip objects created between "now" and the start of the
963 ** real sweep.
964 */
entersweep(lua_State * L)965 static void entersweep (lua_State *L) {
966 global_State *g = G(L);
967 g->gcstate = GCSswpallgc;
968 lua_assert(g->sweepgc == NULL);
969 g->sweepgc = sweeplist(L, &g->allgc, 1);
970 }
971
972
luaC_freeallobjects(lua_State * L)973 void luaC_freeallobjects (lua_State *L) {
974 global_State *g = G(L);
975 separatetobefnz(g, 1); /* separate all objects with finalizers */
976 lua_assert(g->finobj == NULL);
977 callallpendingfinalizers(L);
978 lua_assert(g->tobefnz == NULL);
979 g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */
980 g->gckind = KGC_NORMAL;
981 sweepwholelist(L, &g->finobj);
982 sweepwholelist(L, &g->allgc);
983 sweepwholelist(L, &g->fixedgc); /* collect fixed objects */
984 lua_assert(g->strt.nuse == 0);
985 }
986
987
atomic(lua_State * L)988 static l_mem atomic (lua_State *L) {
989 global_State *g = G(L);
990 l_mem work;
991 GCObject *origweak, *origall;
992 GCObject *grayagain = g->grayagain; /* save original list */
993 lua_assert(g->ephemeron == NULL && g->weak == NULL);
994 lua_assert(!iswhite(g->mainthread));
995 g->gcstate = GCSinsideatomic;
996 g->GCmemtrav = 0; /* start counting work */
997 markobject(g, L); /* mark running thread */
998 /* registry and global metatables may be changed by API */
999 markvalue(g, &g->l_registry);
1000 markmt(g); /* mark global metatables */
1001 /* remark occasional upvalues of (maybe) dead threads */
1002 remarkupvals(g);
1003 propagateall(g); /* propagate changes */
1004 work = g->GCmemtrav; /* stop counting (do not recount 'grayagain') */
1005 g->gray = grayagain;
1006 propagateall(g); /* traverse 'grayagain' list */
1007 g->GCmemtrav = 0; /* restart counting */
1008 convergeephemerons(g);
1009 /* at this point, all strongly accessible objects are marked. */
1010 /* Clear values from weak tables, before checking finalizers */
1011 clearvalues(g, g->weak, NULL);
1012 clearvalues(g, g->allweak, NULL);
1013 origweak = g->weak; origall = g->allweak;
1014 work += g->GCmemtrav; /* stop counting (objects being finalized) */
1015 separatetobefnz(g, 0); /* separate objects to be finalized */
1016 g->gcfinnum = 1; /* there may be objects to be finalized */
1017 markbeingfnz(g); /* mark objects that will be finalized */
1018 propagateall(g); /* remark, to propagate 'resurrection' */
1019 g->GCmemtrav = 0; /* restart counting */
1020 convergeephemerons(g);
1021 /* at this point, all resurrected objects are marked. */
1022 /* remove dead objects from weak tables */
1023 clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */
1024 clearkeys(g, g->allweak, NULL); /* clear keys from all 'allweak' tables */
1025 /* clear values from resurrected weak tables */
1026 clearvalues(g, g->weak, origweak);
1027 clearvalues(g, g->allweak, origall);
1028 luaS_clearcache(g);
1029 g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
1030 work += g->GCmemtrav; /* complete counting */
1031 return work; /* estimate of memory marked by 'atomic' */
1032 }
1033
1034
sweepstep(lua_State * L,global_State * g,int nextstate,GCObject ** nextlist)1035 static lu_mem sweepstep (lua_State *L, global_State *g,
1036 int nextstate, GCObject **nextlist) {
1037 if (g->sweepgc) {
1038 l_mem olddebt = g->GCdebt;
1039 g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
1040 g->GCestimate += g->GCdebt - olddebt; /* update estimate */
1041 if (g->sweepgc) /* is there still something to sweep? */
1042 return (GCSWEEPMAX * GCSWEEPCOST);
1043 }
1044 /* else enter next state */
1045 g->gcstate = nextstate;
1046 g->sweepgc = nextlist;
1047 return 0;
1048 }
1049
1050
singlestep(lua_State * L)1051 static lu_mem singlestep (lua_State *L) {
1052 global_State *g = G(L);
1053 switch (g->gcstate) {
1054 case GCSpause: {
1055 g->GCmemtrav = g->strt.size * sizeof(GCObject*);
1056 restartcollection(g);
1057 g->gcstate = GCSpropagate;
1058 return g->GCmemtrav;
1059 }
1060 case GCSpropagate: {
1061 g->GCmemtrav = 0;
1062 lua_assert(g->gray);
1063 propagatemark(g);
1064 if (g->gray == NULL) /* no more gray objects? */
1065 g->gcstate = GCSatomic; /* finish propagate phase */
1066 return g->GCmemtrav; /* memory traversed in this step */
1067 }
1068 case GCSatomic: {
1069 lu_mem work;
1070 propagateall(g); /* make sure gray list is empty */
1071 work = atomic(L); /* work is what was traversed by 'atomic' */
1072 entersweep(L);
1073 g->GCestimate = gettotalbytes(g); /* first estimate */;
1074 return work;
1075 }
1076 case GCSswpallgc: { /* sweep "regular" objects */
1077 return sweepstep(L, g, GCSswpfinobj, &g->finobj);
1078 }
1079 case GCSswpfinobj: { /* sweep objects with finalizers */
1080 return sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
1081 }
1082 case GCSswptobefnz: { /* sweep objects to be finalized */
1083 return sweepstep(L, g, GCSswpend, NULL);
1084 }
1085 case GCSswpend: { /* finish sweeps */
1086 makewhite(g, g->mainthread); /* sweep main thread */
1087 checkSizes(L, g);
1088 g->gcstate = GCScallfin;
1089 return 0;
1090 }
1091 case GCScallfin: { /* call remaining finalizers */
1092 if (g->tobefnz && g->gckind != KGC_EMERGENCY) {
1093 int n = runafewfinalizers(L);
1094 return (n * GCFINALIZECOST);
1095 }
1096 else { /* emergency mode or no more finalizers */
1097 g->gcstate = GCSpause; /* finish collection */
1098 return 0;
1099 }
1100 }
1101 default: lua_assert(0); return 0;
1102 }
1103 }
1104
1105
1106 /*
1107 ** advances the garbage collector until it reaches a state allowed
1108 ** by 'statemask'
1109 */
luaC_runtilstate(lua_State * L,int statesmask)1110 void luaC_runtilstate (lua_State *L, int statesmask) {
1111 global_State *g = G(L);
1112 while (!testbit(statesmask, g->gcstate))
1113 singlestep(L);
1114 }
1115
1116
1117 /*
1118 ** get GC debt and convert it from Kb to 'work units' (avoid zero debt
1119 ** and overflows)
1120 */
getdebt(global_State * g)1121 static l_mem getdebt (global_State *g) {
1122 l_mem debt = g->GCdebt;
1123 int stepmul = g->gcstepmul;
1124 if (debt <= 0) return 0; /* minimal debt */
1125 else {
1126 debt = (debt / STEPMULADJ) + 1;
1127 debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM;
1128 return debt;
1129 }
1130 }
1131
1132 /*
1133 ** performs a basic GC step when collector is running
1134 */
luaC_step(lua_State * L)1135 void luaC_step (lua_State *L) {
1136 global_State *g = G(L);
1137 l_mem debt = getdebt(g); /* GC deficit (be paid now) */
1138 if (!g->gcrunning) { /* not running? */
1139 luaE_setdebt(g, -GCSTEPSIZE * 10); /* avoid being called too often */
1140 return;
1141 }
1142 do { /* repeat until pause or enough "credit" (negative debt) */
1143 lu_mem work = singlestep(L); /* perform one single step */
1144 debt -= work;
1145 } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);
1146 if (g->gcstate == GCSpause)
1147 setpause(g); /* pause until next cycle */
1148 else {
1149 debt = (debt / g->gcstepmul) * STEPMULADJ; /* convert 'work units' to Kb */
1150 luaE_setdebt(g, debt);
1151 runafewfinalizers(L);
1152 }
1153 }
1154
1155
1156 /*
1157 ** Performs a full GC cycle; if 'isemergency', set a flag to avoid
1158 ** some operations which could change the interpreter state in some
1159 ** unexpected ways (running finalizers and shrinking some structures).
1160 ** Before running the collection, check 'keepinvariant'; if it is true,
1161 ** there may be some objects marked as black, so the collector has
1162 ** to sweep all objects to turn them back to white (as white has not
1163 ** changed, nothing will be collected).
1164 */
luaC_fullgc(lua_State * L,int isemergency)1165 void luaC_fullgc (lua_State *L, int isemergency) {
1166 global_State *g = G(L);
1167 lua_assert(g->gckind == KGC_NORMAL);
1168 if (isemergency) g->gckind = KGC_EMERGENCY; /* set flag */
1169 if (keepinvariant(g)) { /* black objects? */
1170 entersweep(L); /* sweep everything to turn them back to white */
1171 }
1172 /* finish any pending sweep phase to start a new cycle */
1173 luaC_runtilstate(L, bitmask(GCSpause));
1174 luaC_runtilstate(L, ~bitmask(GCSpause)); /* start new collection */
1175 luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */
1176 /* estimate must be correct after a full GC cycle */
1177 lua_assert(g->GCestimate == gettotalbytes(g));
1178 luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */
1179 g->gckind = KGC_NORMAL;
1180 setpause(g);
1181 }
1182
1183 /* }====================================================== */
1184
lua_mlock(lua_State * L,int en)1185 LUA_API void lua_mlock (lua_State *L, int en) {
1186 global_State *g = G(L);
1187 g->gcmlock = en;
1188 }
1189