Lua TeamLua 5.3.0-rc2f4a972711 years agoHistory
1159 lines · 34.9 KB · C
RawDownload
/*** $Id: lgc.c,v 2.201 2014/12/20 13:58:15 roberto Exp $** Garbage Collector** See Copyright Notice in lua.h*/ #define lgc_c#define LUA_CORE #include "lprefix.h"  #include <string.h> #include "lua.h" #include "ldebug.h"#include "ldo.h"#include "lfunc.h"#include "lgc.h"#include "lmem.h"#include "lobject.h"#include "lstate.h"#include "lstring.h"#include "ltable.h"#include "ltm.h"  /*** internal state for collector while inside the atomic phase. The** collector should never be in this state while running regular code.*/#define GCSinsideatomic		(GCSpause + 1) /*** cost of sweeping one element (the size of a small object divided** by some adjust for the sweep speed)*/#define GCSWEEPCOST	((sizeof(TString) + 4) / 4) /* maximum number of elements to sweep in each single step */#define GCSWEEPMAX	(cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4)) /* cost of calling one finalizer */#define GCFINALIZECOST	GCSWEEPCOST  /*** macro to adjust 'stepmul': 'stepmul' is actually used like** 'stepmul / STEPMULADJ' (value chosen by tests)*/#define STEPMULADJ		200  /*** macro to adjust 'pause': 'pause' is actually used like** 'pause / PAUSEADJ' (value chosen by tests)*/#define PAUSEADJ		100  /*** 'makewhite' erases all color bits then sets only the current white** bit*/#define maskcolors	(~(bitmask(BLACKBIT) | WHITEBITS))#define makewhite(g,x)	\ (x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g))) #define white2gray(x)	resetbits(x->marked, WHITEBITS)#define black2gray(x)	resetbit(x->marked, BLACKBIT)  #define valiswhite(x)   (iscollectable(x) && iswhite(gcvalue(x))) #define checkdeadkey(n)	lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))  #define checkconsistency(obj)  \  lua_longassert(!iscollectable(obj) || righttt(obj))  #define markvalue(g,o) { checkconsistency(o); \  if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); } #define markobject(g,t) \  { if ((t) && iswhite(t)) reallymarkobject(g, obj2gco(t)); } static void reallymarkobject (global_State *g, GCObject *o);  /*** {======================================================** Generic functions** =======================================================*/  /*** one after last element in a hash array*/#define gnodelast(h)	gnode(h, cast(size_t, sizenode(h)))  /*** link collectable object 'o' into list pointed by 'p'*/#define linkgclist(o,p)	((o)->gclist = (p), (p) = obj2gco(o))  /*** if key is not marked, mark its entry as dead (therefore removing it** from the table)*/static void removeentry (Node *n) {  lua_assert(ttisnil(gval(n)));  if (valiswhite(gkey(n)))    setdeadvalue(wgkey(n));  /* unused and unmarked key; remove it */}  /*** tells whether a key or value can be cleared from a weak** table. Non-collectable objects are never removed from weak** tables. Strings behave as 'values', so are never removed too. for** other objects: if really collected, cannot keep them; for objects** being finalized, keep them in keys, but not in values*/static int iscleared (global_State *g, const TValue *o) {  if (!iscollectable(o)) return 0;  else if (ttisstring(o)) {    markobject(g, tsvalue(o));  /* strings are 'values', so are never weak */    return 0;  }  else return iswhite(gcvalue(o));}  /*** barrier that moves collector forward, that is, mark the white object** being pointed by a black object. (If in sweep phase, clear the black** object to white [sweep it] to avoid other barrier calls for this** same object.)*/void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {  global_State *g = G(L);  lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));  if (keepinvariant(g))  /* must keep invariant? */    reallymarkobject(g, v);  /* restore invariant */  else {  /* sweep phase */    lua_assert(issweepphase(g));    makewhite(g, o);  /* mark main obj. as white to avoid other barriers */  }}  /*** barrier that moves collector backward, that is, mark the black object** pointing to a white object as gray again.*/void luaC_barrierback_ (lua_State *L, Table *t) {  global_State *g = G(L);  lua_assert(isblack(t) && !isdead(g, t));  black2gray(t);  /* make table gray (again) */  linkgclist(t, g->grayagain);}  /*** barrier for assignments to closed upvalues. Because upvalues are** shared among closures, it is impossible to know the color of all** closures pointing to it. So, we assume that the object being assigned** must be marked.*/void luaC_upvalbarrier_ (lua_State *L, UpVal *uv) {  global_State *g = G(L);  GCObject *o = gcvalue(uv->v);  lua_assert(!upisopen(uv));  /* ensured by macro luaC_upvalbarrier */  if (keepinvariant(g))    markobject(g, o);}  void luaC_fix (lua_State *L, GCObject *o) {  global_State *g = G(L);  lua_assert(g->allgc == o);  /* object must be 1st in 'allgc' list! */  white2gray(o);  /* they will be gray forever */  g->allgc = o->next;  /* remove object from 'allgc' list */  o->next = g->fixedgc;  /* link it to 'fixedgc' list */  g->fixedgc = o;}  /*** create a new collectable object (with given type and size) and link** it to 'allgc' list.*/GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {  global_State *g = G(L);  GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz));  o->marked = luaC_white(g);  o->tt = tt;  o->next = g->allgc;  g->allgc = o;  return o;} /* }====================================================== */   /*** {======================================================** Mark functions** =======================================================*/  /*** mark an object. Userdata, strings, and closed upvalues are visited** and turned black here. Other objects are marked gray and added** to appropriate list to be visited (and turned black) later. (Open** upvalues are already linked in 'headuv' list.)*/static void reallymarkobject (global_State *g, GCObject *o) { reentry:  white2gray(o);  switch (o->tt) {    case LUA_TSHRSTR:    case LUA_TLNGSTR: {      gray2black(o);      g->GCmemtrav += sizestring(gco2ts(o));      break;    }    case LUA_TUSERDATA: {      TValue uvalue;      markobject(g, gco2u(o)->metatable);  /* mark its metatable */      gray2black(o);      g->GCmemtrav += sizeudata(gco2u(o));      getuservalue(g->mainthread, gco2u(o), &uvalue);      if (valiswhite(&uvalue)) {  /* markvalue(g, &uvalue); */        o = gcvalue(&uvalue);        goto reentry;      }      break;    }    case LUA_TLCL: {      linkgclist(gco2lcl(o), g->gray);      break;    }    case LUA_TCCL: {      linkgclist(gco2ccl(o), g->gray);      break;    }    case LUA_TTABLE: {      linkgclist(gco2t(o), g->gray);      break;    }    case LUA_TTHREAD: {      linkgclist(gco2th(o), g->gray);      break;    }    case LUA_TPROTO: {      linkgclist(gco2p(o), g->gray);      break;    }    default: lua_assert(0); break;  }}  /*** mark metamethods for basic types*/static void markmt (global_State *g) {  int i;  for (i=0; i < LUA_NUMTAGS; i++)    markobject(g, g->mt[i]);}  /*** mark all objects in list of being-finalized*/static void markbeingfnz (global_State *g) {  GCObject *o;  for (o = g->tobefnz; o != NULL; o = o->next)    markobject(g, o);}  /*** Mark all values stored in marked open upvalues from non-marked threads.** (Values from marked threads were already marked when traversing the** thread.) Remove from the list threads that no longer have upvalues and** not-marked threads.*/static void remarkupvals (global_State *g) {  lua_State *thread;  lua_State **p = &g->twups;  while ((thread = *p) != NULL) {    lua_assert(!isblack(thread));  /* threads are never black */    if (isgray(thread) && thread->openupval != NULL)      p = &thread->twups;  /* keep marked thread with upvalues in the list */    else {  /* thread is not marked or without upvalues */      UpVal *uv;      *p = thread->twups;  /* remove thread from the list */      thread->twups = thread;  /* mark that it is out of list */      for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {        if (uv->u.open.touched) {          markvalue(g, uv->v);  /* remark upvalue's value */          uv->u.open.touched = 0;        }      }    }  }}  /*** mark root set and reset all gray lists, to start a new collection*/static void restartcollection (global_State *g) {  g->gray = g->grayagain = NULL;  g->weak = g->allweak = g->ephemeron = NULL;  markobject(g, g->mainthread);  markvalue(g, &g->l_registry);  markmt(g);  markbeingfnz(g);  /* mark any finalizing object left from previous cycle */} /* }====================================================== */  /*** {======================================================** Traverse functions** =======================================================*/ /*** Traverse a table with weak values and link it to proper list. During** propagate phase, keep it in 'grayagain' list, to be revisited in the** atomic phase. In the atomic phase, if table has any white value,** put it in 'weak' list, to be cleared.*/static void traverseweakvalue (global_State *g, Table *h) {  Node *n, *limit = gnodelast(h);  /* if there is array part, assume it may have white values (it is not     worth traversing it now just to check) */  int hasclears = (h->sizearray > 0);  for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */    checkdeadkey(n);    if (ttisnil(gval(n)))  /* entry is empty? */      removeentry(n);  /* remove it */    else {      lua_assert(!ttisnil(gkey(n)));      markvalue(g, gkey(n));  /* mark key */      if (!hasclears && iscleared(g, gval(n)))  /* is there a white value? */        hasclears = 1;  /* table will have to be cleared */    }  }  if (g->gcstate == GCSpropagate)    linkgclist(h, g->grayagain);  /* must retraverse it in atomic phase */  else if (hasclears)    linkgclist(h, g->weak);  /* has to be cleared later */}  /*** Traverse an ephemeron table and link it to proper list. Returns true** iff any object was marked during this traversal (which implies that** convergence has to continue). During propagation phase, keep table** in 'grayagain' list, to be visited again in the atomic phase. In** the atomic phase, if table has any white->white entry, it has to** be revisited during ephemeron convergence (as that key may turn** black). Otherwise, if it has any white key, table has to be cleared** (in the atomic phase).*/static int traverseephemeron (global_State *g, Table *h) {  int marked = 0;  /* true if an object is marked in this traversal */  int hasclears = 0;  /* true if table has white keys */  int hasww = 0;  /* true if table has entry "white-key -> white-value" */  Node *n, *limit = gnodelast(h);  unsigned int i;  /* traverse array part */  for (i = 0; i < h->sizearray; i++) {    if (valiswhite(&h->array[i])) {      marked = 1;      reallymarkobject(g, gcvalue(&h->array[i]));    }  }  /* traverse hash part */  for (n = gnode(h, 0); n < limit; n++) {    checkdeadkey(n);    if (ttisnil(gval(n)))  /* entry is empty? */      removeentry(n);  /* remove it */    else if (iscleared(g, gkey(n))) {  /* key is not marked (yet)? */      hasclears = 1;  /* table must be cleared */      if (valiswhite(gval(n)))  /* value not marked yet? */        hasww = 1;  /* white-white entry */    }    else if (valiswhite(gval(n))) {  /* value not marked yet? */      marked = 1;      reallymarkobject(g, gcvalue(gval(n)));  /* mark it now */    }  }  /* link table into proper list */  if (g->gcstate == GCSpropagate)    linkgclist(h, g->grayagain);  /* must retraverse it in atomic phase */  else if (hasww)  /* table has white->white entries? */    linkgclist(h, g->ephemeron);  /* have to propagate again */  else if (hasclears)  /* table has white keys? */    linkgclist(h, g->allweak);  /* may have to clean white keys */  return marked;}  static void traversestrongtable (global_State *g, Table *h) {  Node *n, *limit = gnodelast(h);  unsigned int i;  for (i = 0; i < h->sizearray; i++)  /* traverse array part */    markvalue(g, &h->array[i]);  for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */    checkdeadkey(n);    if (ttisnil(gval(n)))  /* entry is empty? */      removeentry(n);  /* remove it */    else {      lua_assert(!ttisnil(gkey(n)));      markvalue(g, gkey(n));  /* mark key */      markvalue(g, gval(n));  /* mark value */    }  }}  static lu_mem traversetable (global_State *g, Table *h) {  const char *weakkey, *weakvalue;  const TValue *mode = gfasttm(g, h->metatable, TM_MODE);  markobject(g, h->metatable);  if (mode && ttisstring(mode) &&  /* is there a weak mode? */      ((weakkey = strchr(svalue(mode), 'k')),       (weakvalue = strchr(svalue(mode), 'v')),       (weakkey || weakvalue))) {  /* is really weak? */    black2gray(h);  /* keep table gray */    if (!weakkey)  /* strong keys? */      traverseweakvalue(g, h);    else if (!weakvalue)  /* strong values? */      traverseephemeron(g, h);    else  /* all weak */      linkgclist(h, g->allweak);  /* nothing to traverse now */  }  else  /* not weak */    traversestrongtable(g, h);  return sizeof(Table) + sizeof(TValue) * h->sizearray +                         sizeof(Node) * cast(size_t, sizenode(h));}  static int traverseproto (global_State *g, Proto *f) {  int i;  if (f->cache && iswhite(f->cache))    f->cache = NULL;  /* allow cache to be collected */  markobject(g, f->source);  for (i = 0; i < f->sizek; i++)  /* mark literals */    markvalue(g, &f->k[i]);  for (i = 0; i < f->sizeupvalues; i++)  /* mark upvalue names */    markobject(g, f->upvalues[i].name);  for (i = 0; i < f->sizep; i++)  /* mark nested protos */    markobject(g, f->p[i]);  for (i = 0; i < f->sizelocvars; i++)  /* mark local-variable names */    markobject(g, f->locvars[i].varname);  return sizeof(Proto) + sizeof(Instruction) * f->sizecode +                         sizeof(Proto *) * f->sizep +                         sizeof(TValue) * f->sizek +                         sizeof(int) * f->sizelineinfo +                         sizeof(LocVar) * f->sizelocvars +                         sizeof(Upvaldesc) * f->sizeupvalues;}  static lu_mem traverseCclosure (global_State *g, CClosure *cl) {  int i;  for (i = 0; i < cl->nupvalues; i++)  /* mark its upvalues */    markvalue(g, &cl->upvalue[i]);  return sizeCclosure(cl->nupvalues);} /*** open upvalues point to values in a thread, so those values should** be marked when the thread is traversed except in the atomic phase** (because then the value cannot be changed by the thread and the** thread may not be traversed again)*/static lu_mem traverseLclosure (global_State *g, LClosure *cl) {  int i;  markobject(g, cl->p);  /* mark its prototype */  for (i = 0; i < cl->nupvalues; i++) {  /* mark its upvalues */    UpVal *uv = cl->upvals[i];    if (uv != NULL) {

Lines 1–500 of 1159.