LCOV - code coverage report
Current view: top level - external/lua/src - lgc.c (source / functions) Hit Total Coverage
Test: rapport Lines: 432 794 54.4 %
Date: 2021-12-10 16:22:55 Functions: 49 72 68.1 %
Branches: 204 466 43.8 %

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

Generated by: LCOV version 1.15