Coverage Report

Created: 2025-07-18 07:03

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