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