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