lgc.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  1. /*
  2. ** $Id: lgc.c,v 2.104 2010/11/26 14:32:31 roberto Exp roberto $
  3. ** Garbage Collector
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <string.h>
  7. #define lgc_c
  8. #define LUA_CORE
  9. #include "lua.h"
  10. #include "ldebug.h"
  11. #include "ldo.h"
  12. #include "lfunc.h"
  13. #include "lgc.h"
  14. #include "lmem.h"
  15. #include "lobject.h"
  16. #include "lstate.h"
  17. #include "lstring.h"
  18. #include "ltable.h"
  19. #include "ltm.h"
  20. /* how much to allocate before next GC step */
  21. #define GCSTEPSIZE 1024
  22. /* maximum number of elements to sweep in each single step */
  23. #define GCSWEEPMAX 40
  24. /* cost of sweeping one element */
  25. #define GCSWEEPCOST 1
  26. /* maximum number of finalizers to call in each GC step */
  27. #define GCFINALIZENUM 4
  28. /* cost of marking the root set */
  29. #define GCROOTCOST 10
  30. /* cost of atomic step */
  31. #define GCATOMICCOST 1000
  32. /* basic cost to traverse one object (to be added to the links the
  33. object may have) */
  34. #define TRAVCOST 5
  35. /*
  36. ** standard negative debt for GC; a reasonable "time" to wait before
  37. ** starting a new cycle
  38. */
  39. #define stddebt(g) (-cast(l_mem, g->totalbytes/100) * g->gcpause)
  40. /*
  41. ** 'makewhite' erases all color bits plus the old bit and then
  42. ** sets only the current white bit
  43. */
  44. #define maskcolors (~(bit2mask(BLACKBIT, OLDBIT) | WHITEBITS))
  45. #define makewhite(g,x) \
  46. (gch(x)->marked = cast_byte((gch(x)->marked & maskcolors) | luaC_white(g)))
  47. #define white2gray(x) resetbits(gch(x)->marked, WHITEBITS)
  48. #define black2gray(x) resetbit(gch(x)->marked, BLACKBIT)
  49. #define stringmark(s) ((void)((s) && resetbits((s)->tsv.marked, WHITEBITS)))
  50. #define isfinalized(x) testbit(gch(x)->marked, FINALIZEDBIT)
  51. #define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))
  52. #define markvalue(g,o) { checkconsistency(o); \
  53. if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
  54. #define markobject(g,t) { if ((t) && iswhite(obj2gco(t))) \
  55. reallymarkobject(g, obj2gco(t)); }
  56. static void reallymarkobject (global_State *g, GCObject *o);
  57. /*
  58. ** {======================================================
  59. ** Generic functions
  60. ** =======================================================
  61. */
  62. /*
  63. ** link table 'h' into list pointed by 'p'
  64. */
  65. #define linktable(h,p) ((h)->gclist = *(p), *(p) = obj2gco(h))
  66. /*
  67. ** mark a table entry as dead (therefore removing it from the table)
  68. */
  69. static void removeentry (Node *n) {
  70. lua_assert(ttisnil(gval(n)));
  71. if (iscollectable(gkey(n)))
  72. setdeadvalue(gkey(n)); /* dead key; remove it */
  73. }
  74. /*
  75. ** tells whether a key or value can be cleared from a weak
  76. ** table. Non-collectable objects are never removed from weak
  77. ** tables. Strings behave as `values', so are never removed too. for
  78. ** other objects: if really collected, cannot keep them; for objects
  79. ** being finalized, keep them in keys, but not in values
  80. */
  81. static int iscleared (const TValue *o, int iskey) {
  82. if (!iscollectable(o)) return 0;
  83. else if (ttisstring(o)) {
  84. stringmark(rawtsvalue(o)); /* strings are `values', so are never weak */
  85. return 0;
  86. }
  87. else return iswhite(gcvalue(o)) || (!iskey && isfinalized(gcvalue(o)));
  88. }
  89. /*
  90. ** barrier that moves collector forward, that is, mark the white object
  91. ** being pointed by a black object.
  92. */
  93. void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
  94. global_State *g = G(L);
  95. lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
  96. lua_assert(isgenerational(g) || g->gcstate != GCSpause);
  97. lua_assert(gch(o)->tt != LUA_TTABLE);
  98. if (keepinvariant(g)) /* must keep invariant? */
  99. reallymarkobject(g, v); /* restore invariant */
  100. else { /* sweep phase */
  101. lua_assert(issweepphase(g));
  102. makewhite(g, o); /* mark main obj. as white to avoid other barriers */
  103. }
  104. }
  105. /*
  106. ** barrier that moves collector backward, that is, mark the black object
  107. ** pointing to a white object as gray again. (Current implementation
  108. ** only works for tables; access to 'gclist' is not uniform across
  109. ** different types.)
  110. */
  111. void luaC_barrierback_ (lua_State *L, GCObject *o) {
  112. global_State *g = G(L);
  113. lua_assert(isblack(o) && !isdead(g, o));
  114. black2gray(o); /* make object gray (again) */
  115. gco2t(o)->gclist = g->grayagain;
  116. g->grayagain = o;
  117. }
  118. /*
  119. ** barrier for prototypes. When creating first closure (cache is
  120. ** NULL), use a forward barrier; this may be the only closure of the
  121. ** prototype (if it is a "regular" function, with a single instance)
  122. ** and the prototype may be big, so it is better to avoid traversing
  123. ** it again. Otherwise, use a backward barrier, to avoid marking all
  124. ** possible instances.
  125. */
  126. LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c) {
  127. global_State *g = G(L);
  128. lua_assert(isblack(obj2gco(p)));
  129. if (p->cache == NULL) { /* first time? */
  130. luaC_objbarrier(L, p, c);
  131. }
  132. else { /* use a backward barrier */
  133. black2gray(obj2gco(p)); /* make prototype gray (again) */
  134. p->gclist = g->grayagain;
  135. g->grayagain = obj2gco(p);
  136. }
  137. }
  138. /*
  139. ** check color (and invariants) for an upvalue that was closed,
  140. ** i.e., moved into the 'allgc' list
  141. */
  142. void luaC_checkupvalcolor (global_State *g, UpVal *uv) {
  143. GCObject *o = obj2gco(uv);
  144. lua_assert(!isblack(o)); /* open upvalues are never black */
  145. if (isgray(o)) {
  146. if (keepinvariant(g)) {
  147. resetoldbit(o); /* see MOVE OLD rule */
  148. gray2black(o); /* it is being visited now */
  149. markvalue(g, uv->v);
  150. }
  151. else {
  152. lua_assert(issweepphase(g));
  153. makewhite(g, o);
  154. }
  155. }
  156. }
  157. /*
  158. ** create a new collectable object (with given type and size) and link
  159. ** it to '*list'. 'offset' tells how many bytes to allocate before the
  160. ** object itself (used only by states).
  161. */
  162. GCObject *luaC_newobj (lua_State *L, int tt, size_t sz, GCObject **list,
  163. int offset) {
  164. global_State *g = G(L);
  165. GCObject *o = obj2gco(cast(char *, luaM_newobject(L, tt, sz)) + offset);
  166. if (list == NULL)
  167. list = &g->allgc; /* standard list for collectable objects */
  168. gch(o)->marked = luaC_white(g);
  169. gch(o)->tt = tt;
  170. gch(o)->next = *list;
  171. *list = o;
  172. return o;
  173. }
  174. /* }====================================================== */
  175. /*
  176. ** {======================================================
  177. ** Mark functions
  178. ** =======================================================
  179. */
  180. /*
  181. ** mark an object. Userdata and closed upvalues are visited and turned
  182. ** black here. Strings remain gray (it is the same as making them
  183. ** black). Other objects are marked gray and added to appropriate list
  184. ** to be visited (and turned black) later. (Open upvalues are already
  185. ** linked in 'headuv' list.)
  186. */
  187. static void reallymarkobject (global_State *g, GCObject *o) {
  188. lua_assert(iswhite(o) && !isdead(g, o));
  189. white2gray(o);
  190. switch (gch(o)->tt) {
  191. case LUA_TSTRING: {
  192. return; /* for strings, gray is as good as black */
  193. }
  194. case LUA_TUSERDATA: {
  195. Table *mt = gco2u(o)->metatable;
  196. markobject(g, mt);
  197. markobject(g, gco2u(o)->env);
  198. gray2black(o); /* all pointers marked */
  199. return;
  200. }
  201. case LUA_TUPVAL: {
  202. UpVal *uv = gco2uv(o);
  203. markvalue(g, uv->v);
  204. if (uv->v == &uv->u.value) /* closed? (open upvalues remain gray) */
  205. gray2black(o); /* make it black */
  206. return;
  207. }
  208. case LUA_TFUNCTION: {
  209. gco2cl(o)->c.gclist = g->gray;
  210. g->gray = o;
  211. break;
  212. }
  213. case LUA_TTABLE: {
  214. linktable(gco2t(o), &g->gray);
  215. break;
  216. }
  217. case LUA_TTHREAD: {
  218. gco2th(o)->gclist = g->gray;
  219. g->gray = o;
  220. break;
  221. }
  222. case LUA_TPROTO: {
  223. gco2p(o)->gclist = g->gray;
  224. g->gray = o;
  225. break;
  226. }
  227. default: lua_assert(0);
  228. }
  229. }
  230. /*
  231. ** mark tag methods for basic types
  232. */
  233. static void markmt (global_State *g) {
  234. int i;
  235. for (i=0; i < LUA_NUMTAGS; i++)
  236. markobject(g, g->mt[i]);
  237. }
  238. /*
  239. ** mark all objects in list of being-finalized
  240. */
  241. static void markbeingfnz (global_State *g) {
  242. GCObject *o;
  243. for (o = g->tobefnz; o != NULL; o = gch(o)->next) {
  244. makewhite(g, o);
  245. reallymarkobject(g, o);
  246. }
  247. }
  248. /*
  249. ** mark all values stored in marked open upvalues. (See comment in
  250. ** 'lstate.h'.)
  251. */
  252. static void remarkupvals (global_State *g) {
  253. UpVal *uv;
  254. for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) {
  255. if (isgray(obj2gco(uv)))
  256. markvalue(g, uv->v);
  257. }
  258. }
  259. /*
  260. ** mark root set and reset all gray lists, to start a new
  261. ** incremental (or full) collection
  262. */
  263. static void markroot (lua_State *L) {
  264. global_State *g = G(L);
  265. g->gray = g->grayagain = NULL;
  266. g->weak = g->allweak = g->ephemeron = NULL;
  267. markobject(g, g->mainthread);
  268. markvalue(g, &g->l_registry);
  269. markmt(g);
  270. markbeingfnz(g); /* mark any finalizing object left from previous cycle */
  271. }
  272. /* }====================================================== */
  273. /*
  274. ** {======================================================
  275. ** Traverse functions
  276. ** =======================================================
  277. */
  278. static void traverseweakvalue (global_State *g, Table *h) {
  279. Node *n, *limit = gnode(h, sizenode(h));
  280. for (n = gnode(h, 0); n < limit; n++) {
  281. checkdeadkey(n);
  282. if (ttisnil(gval(n))) /* entry is empty? */
  283. removeentry(n); /* remove it */
  284. else {
  285. lua_assert(!ttisnil(gkey(n)));
  286. markvalue(g, gkey(n)); /* mark key */
  287. }
  288. }
  289. linktable(h, &g->weak); /* link into appropriate list */
  290. }
  291. static int traverseephemeron (global_State *g, Table *h) {
  292. int marked = 0; /* true if an object is marked in this traversal */
  293. int hasclears = 0; /* true if table has unmarked pairs */
  294. Node *n, *limit = gnode(h, sizenode(h));
  295. int i;
  296. /* traverse array part (numeric keys are 'strong') */
  297. for (i = 0; i < h->sizearray; i++) {
  298. if (valiswhite(&h->array[i])) {
  299. marked = 1;
  300. reallymarkobject(g, gcvalue(&h->array[i]));
  301. }
  302. }
  303. /* traverse hash part */
  304. for (n = gnode(h, 0); n < limit; n++) {
  305. checkdeadkey(n);
  306. if (ttisnil(gval(n))) /* entry is empty? */
  307. removeentry(n); /* remove it */
  308. else if (valiswhite(gval(n))) { /* value not marked yet? */
  309. if (iscleared(gkey(n), 1)) /* key is not marked (yet)? */
  310. hasclears = 1; /* may have to propagate mark from key to value */
  311. else { /* key is marked, so mark value */
  312. marked = 1; /* value was not marked */
  313. reallymarkobject(g, gcvalue(gval(n)));
  314. }
  315. }
  316. }
  317. if (hasclears) /* does table have unmarked pairs? */
  318. linktable(h, &g->ephemeron); /* will have to propagate again */
  319. else /* nothing to propagate */
  320. linktable(h, &g->weak); /* avoid convergence phase */
  321. return marked;
  322. }
  323. static void traversestrongtable (global_State *g, Table *h) {
  324. Node *n, *limit = gnode(h, sizenode(h));
  325. int i;
  326. for (i = 0; i < h->sizearray; i++) /* traverse array part */
  327. markvalue(g, &h->array[i]);
  328. for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
  329. checkdeadkey(n);
  330. if (ttisnil(gval(n))) /* entry is empty? */
  331. removeentry(n); /* remove it */
  332. else {
  333. lua_assert(!ttisnil(gkey(n)));
  334. markvalue(g, gkey(n)); /* mark key */
  335. markvalue(g, gval(n)); /* mark value */
  336. }
  337. }
  338. }
  339. static int traversetable (global_State *g, Table *h) {
  340. const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
  341. markobject(g, h->metatable);
  342. if (mode && ttisstring(mode)) { /* is there a weak mode? */
  343. int weakkey = (strchr(svalue(mode), 'k') != NULL);
  344. int weakvalue = (strchr(svalue(mode), 'v') != NULL);
  345. if (weakkey || weakvalue) { /* is really weak? */
  346. black2gray(obj2gco(h)); /* keep table gray */
  347. if (!weakkey) { /* strong keys? */
  348. traverseweakvalue(g, h);
  349. return TRAVCOST + sizenode(h);
  350. }
  351. else if (!weakvalue) { /* strong values? */
  352. traverseephemeron(g, h);
  353. return TRAVCOST + h->sizearray + sizenode(h);
  354. }
  355. else {
  356. linktable(h, &g->allweak); /* nothing to traverse now */
  357. return TRAVCOST;
  358. }
  359. } /* else go through */
  360. }
  361. traversestrongtable(g, h);
  362. return TRAVCOST + h->sizearray + (2 * sizenode(h));
  363. }
  364. static int traverseproto (global_State *g, Proto *f) {
  365. int i;
  366. if (f->cache && iswhite(obj2gco(f->cache)))
  367. f->cache = NULL; /* allow cache to be collected */
  368. stringmark(f->source);
  369. for (i = 0; i < f->sizek; i++) /* mark literals */
  370. markvalue(g, &f->k[i]);
  371. for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
  372. stringmark(f->upvalues[i].name);
  373. for (i = 0; i < f->sizep; i++) /* mark nested protos */
  374. markobject(g, f->p[i]);
  375. for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
  376. stringmark(f->locvars[i].varname);
  377. return TRAVCOST + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars;
  378. }
  379. static int traverseclosure (global_State *g, Closure *cl) {
  380. if (cl->c.isC) {
  381. int i;
  382. for (i=0; i<cl->c.nupvalues; i++) /* mark its upvalues */
  383. markvalue(g, &cl->c.upvalue[i]);
  384. }
  385. else {
  386. int i;
  387. lua_assert(cl->l.nupvalues == cl->l.p->sizeupvalues);
  388. markobject(g, cl->l.p); /* mark its prototype */
  389. for (i=0; i<cl->l.nupvalues; i++) /* mark its upvalues */
  390. markobject(g, cl->l.upvals[i]);
  391. }
  392. return TRAVCOST + cl->c.nupvalues;
  393. }
  394. static int traversestack (global_State *g, lua_State *L) {
  395. StkId o = L->stack;
  396. if (o == NULL)
  397. return 1; /* stack not completely built yet */
  398. for (; o < L->top; o++)
  399. markvalue(g, o);
  400. if (g->gcstate == GCSatomic) { /* final traversal? */
  401. StkId lim = L->stack + L->stacksize; /* real end of stack */
  402. for (; o < lim; o++) /* clear not-marked stack slice */
  403. setnilvalue(o);
  404. }
  405. return TRAVCOST + cast_int(o - L->stack);
  406. }
  407. /*
  408. ** traverse one gray object, turning it to black (except for threads,
  409. ** which are always gray).
  410. ** Returns number of values traversed.
  411. */
  412. static int propagatemark (global_State *g) {
  413. GCObject *o = g->gray;
  414. lua_assert(isgray(o));
  415. gray2black(o);
  416. switch (gch(o)->tt) {
  417. case LUA_TTABLE: {
  418. Table *h = gco2t(o);
  419. g->gray = h->gclist;
  420. return traversetable(g, h);
  421. }
  422. case LUA_TFUNCTION: {
  423. Closure *cl = gco2cl(o);
  424. g->gray = cl->c.gclist;
  425. return traverseclosure(g, cl);
  426. }
  427. case LUA_TTHREAD: {
  428. lua_State *th = gco2th(o);
  429. g->gray = th->gclist;
  430. th->gclist = g->grayagain;
  431. g->grayagain = o;
  432. black2gray(o);
  433. return traversestack(g, th);
  434. }
  435. case LUA_TPROTO: {
  436. Proto *p = gco2p(o);
  437. g->gray = p->gclist;
  438. return traverseproto(g, p);
  439. }
  440. default: lua_assert(0); return 0;
  441. }
  442. }
  443. static void propagateall (global_State *g) {
  444. while (g->gray) propagatemark(g);
  445. }
  446. static void traverselistofgrays (global_State *g, GCObject **l) {
  447. lua_assert(g->gray == NULL); /* no grays left */
  448. g->gray = *l; /* now 'l' is new gray list */
  449. *l = NULL;
  450. propagateall(g);
  451. }
  452. static void convergeephemerons (global_State *g) {
  453. int changed;
  454. do {
  455. GCObject *w;
  456. GCObject *next = g->ephemeron; /* get ephemeron list */
  457. g->ephemeron = NULL; /* tables will return to this list when traversed */
  458. changed = 0;
  459. while ((w = next) != NULL) {
  460. next = gco2t(w)->gclist;
  461. if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */
  462. propagateall(g); /* propagate changes */
  463. changed = 1; /* will have to revisit all ephemeron tables */
  464. }
  465. }
  466. } while (changed);
  467. }
  468. /* }====================================================== */
  469. /*
  470. ** {======================================================
  471. ** Sweep Functions
  472. ** =======================================================
  473. */
  474. /*
  475. ** clear collected entries from all weaktables in list 'l'
  476. */
  477. static void cleartable (GCObject *l) {
  478. for (; l != NULL; l = gco2t(l)->gclist) {
  479. Table *h = gco2t(l);
  480. Node *n, *limit = gnode(h, sizenode(h));
  481. int i;
  482. for (i = 0; i < h->sizearray; i++) {
  483. TValue *o = &h->array[i];
  484. if (iscleared(o, 0)) /* value was collected? */
  485. setnilvalue(o); /* remove value */
  486. }
  487. for (n = gnode(h, 0); n < limit; n++) {
  488. if (!ttisnil(gval(n)) && /* non-empty entry? */
  489. (iscleared(gkey(n), 1) || iscleared(gval(n), 0))) {
  490. setnilvalue(gval(n)); /* remove value ... */
  491. removeentry(n); /* and remove entry from table */
  492. }
  493. }
  494. }
  495. }
  496. static void freeobj (lua_State *L, GCObject *o) {
  497. switch (gch(o)->tt) {
  498. case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
  499. case LUA_TFUNCTION: luaF_freeclosure(L, gco2cl(o)); break;
  500. case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break;
  501. case LUA_TTABLE: luaH_free(L, gco2t(o)); break;
  502. case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
  503. case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
  504. case LUA_TSTRING: {
  505. G(L)->strt.nuse--;
  506. luaM_freemem(L, o, sizestring(gco2ts(o)));
  507. break;
  508. }
  509. default: lua_assert(0);
  510. }
  511. }
  512. #define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM)
  513. static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);
  514. /*
  515. ** sweep the (open) upvalues of a thread and resize its stack and
  516. ** list of call-info structures.
  517. */
  518. static void sweepthread (lua_State *L, lua_State *L1) {
  519. if (L1->stack == NULL) return; /* stack not completely built yet */
  520. sweepwholelist(L, &L1->openupval); /* sweep open upvalues */
  521. luaE_freeCI(L1); /* free extra CallInfo slots */
  522. /* should not change the stack during an emergency gc cycle */
  523. if (G(L)->gckind != KGC_EMERGENCY)
  524. luaD_shrinkstack(L1);
  525. }
  526. /*
  527. ** sweep at most 'count' elements from a list of GCObjects erasing dead
  528. ** objects, where a dead (not alive) object is one marked with the "old"
  529. ** (non current) white and not fixed.
  530. ** In non-generational mode, change all non-dead objects back to white,
  531. ** preparing for next collection cycle.
  532. ** In generational mode, keep black objects black, and also mark them as
  533. ** old; stop when hitting an old object, as all objects after that
  534. ** one will be old too.
  535. ** When object is a thread, sweep its list of open upvalues too.
  536. */
  537. static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
  538. global_State *g = G(L);
  539. int ow = otherwhite(g);
  540. int toclear, toset; /* bits to clear and to set in all live objects */
  541. int tostop; /* stop sweep when this is true */
  542. if (isgenerational(g)) { /* generational mode? */
  543. toclear = ~0; /* clear nothing */
  544. toset = bitmask(OLDBIT); /* set the old bit of all surviving objects */
  545. tostop = bitmask(OLDBIT); /* do not sweep old generation */
  546. }
  547. else { /* normal mode */
  548. toclear = maskcolors; /* clear all color bits + old bit */
  549. toset = luaC_white(g); /* make object white */
  550. tostop = 0; /* do not stop */
  551. }
  552. while (*p != NULL && count-- > 0) {
  553. GCObject *curr = *p;
  554. int marked = gch(curr)->marked;
  555. if (isdeadm(ow, marked)) { /* is 'curr' dead? */
  556. *p = gch(curr)->next; /* remove 'curr' from list */
  557. freeobj(L, curr); /* erase 'curr' */
  558. }
  559. else {
  560. if (gch(curr)->tt == LUA_TTHREAD)
  561. sweepthread(L, gco2th(curr)); /* sweep thread's upvalues */
  562. if (testbits(marked, tostop)) {
  563. static GCObject *nullp = NULL;
  564. return &nullp; /* stop sweeping this list */
  565. }
  566. /* update marks */
  567. gch(curr)->marked = cast_byte((marked & toclear) | toset);
  568. p = &gch(curr)->next; /* go to next element */
  569. }
  570. }
  571. return p;
  572. }
  573. /* }====================================================== */
  574. /*
  575. ** {======================================================
  576. ** Finalization
  577. ** =======================================================
  578. */
  579. static void checkSizes (lua_State *L) {
  580. global_State *g = G(L);
  581. if (g->gckind != KGC_EMERGENCY) { /* do not change sizes in emergency */
  582. int hs = g->strt.size / 2; /* half the size of the string table */
  583. if (g->strt.nuse < cast(lu_int32, hs)) /* using less than that half? */
  584. luaS_resize(L, hs); /* halve its size */
  585. luaZ_freebuffer(L, &g->buff); /* free concatenation buffer */
  586. }
  587. }
  588. static GCObject *udata2finalize (global_State *g) {
  589. GCObject *o = g->tobefnz; /* get first element */
  590. lua_assert(isfinalized(o));
  591. g->tobefnz = gch(o)->next; /* remove it from 'tobefnz' list */
  592. gch(o)->next = g->allgc; /* return it to 'allgc' list */
  593. g->allgc = o;
  594. resetbit(gch(o)->marked, SEPARATED); /* mark that it is not in 'tobefnz' */
  595. lua_assert(!isold(o)); /* see MOVE OLD rule */
  596. if (!keepinvariant(g)) /* not keeping invariant? */
  597. makewhite(g, o); /* "sweep" object */
  598. return o;
  599. }
  600. static void dothecall (lua_State *L, void *ud) {
  601. UNUSED(ud);
  602. luaD_call(L, L->top - 2, 0, 0);
  603. }
  604. static void GCTM (lua_State *L, int propagateerrors) {
  605. global_State *g = G(L);
  606. const TValue *tm;
  607. TValue v;
  608. setgcovalue(L, &v, udata2finalize(g));
  609. tm = luaT_gettmbyobj(L, &v, TM_GC);
  610. if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */
  611. int status;
  612. lu_byte oldah = L->allowhook;
  613. lu_mem oldd = g->GCdebt;
  614. L->allowhook = 0; /* stop debug hooks during GC tag method */
  615. stopgc(g); /* avoid GC steps */
  616. setobj2s(L, L->top, tm); /* push finalizer... */
  617. setobj2s(L, L->top + 1, &v); /* ... and its argument */
  618. L->top += 2; /* and (next line) call the finalizer */
  619. status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
  620. L->allowhook = oldah; /* restore hooks */
  621. g->GCdebt = oldd; /* restore threshold */
  622. if (status != LUA_OK && propagateerrors) { /* error while running __gc? */
  623. if (status == LUA_ERRRUN) { /* is there an error msg.? */
  624. luaO_pushfstring(L, "error in __gc tag method (%s)",
  625. lua_tostring(L, -1));
  626. status = LUA_ERRGCMM; /* error in __gc metamethod */
  627. }
  628. luaD_throw(L, status); /* re-send error */
  629. }
  630. }
  631. }
  632. /*
  633. ** move all unreachable objects that need finalization from list 'finobj'
  634. ** to list 'tobefnz'
  635. */
  636. void luaC_separateudata (lua_State *L, int all) {
  637. global_State *g = G(L);
  638. GCObject **p = &g->finobj;
  639. GCObject *curr;
  640. GCObject **lastnext = &g->tobefnz;
  641. /* find last 'next' field in 'tobefnz' list (to add elements in its end) */
  642. while (*lastnext != NULL)
  643. lastnext = &gch(*lastnext)->next;
  644. while ((curr = *p) != NULL) { /* traverse all finalizable objects */
  645. lua_assert(!isfinalized(curr));
  646. lua_assert(testbit(gch(curr)->marked, SEPARATED));
  647. if (!(all || iswhite(curr))) /* not being collected? */
  648. p = &gch(curr)->next; /* don't bother with it */
  649. else {
  650. l_setbit(gch(curr)->marked, FINALIZEDBIT); /* won't be finalized again */
  651. *p = gch(curr)->next; /* remove 'curr' from 'finobj' list */
  652. gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */
  653. *lastnext = curr;
  654. lastnext = &gch(curr)->next;
  655. }
  656. }
  657. }
  658. /*
  659. ** if object 'o' has a finalizer, remove it from 'allgc' list (must
  660. ** search the list to find it) and link it in 'finobj' list.
  661. */
  662. void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
  663. global_State *g = G(L);
  664. if (testbit(gch(o)->marked, SEPARATED) || /* obj. is already separated... */
  665. isfinalized(o) || /* ... or is finalized... */
  666. gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */
  667. return; /* nothing to be done */
  668. else { /* move 'o' to 'finobj' list */
  669. GCObject **p;
  670. for (p = &g->allgc; *p != o; p = &gch(*p)->next) ;
  671. *p = gch(o)->next; /* remove 'o' from root list */
  672. gch(o)->next = g->finobj; /* link it in list 'finobj' */
  673. g->finobj = o;
  674. l_setbit(gch(o)->marked, SEPARATED); /* mark it as such */
  675. resetoldbit(o); /* see MOVE OLD rule */
  676. }
  677. }
  678. /* }====================================================== */
  679. /*
  680. ** {======================================================
  681. ** GC control
  682. ** =======================================================
  683. */
  684. #define sweepphases \
  685. (bitmask(GCSsweepstring) | bitmask(GCSsweepudata) | bitmask(GCSsweep))
  686. /*
  687. ** change GC mode
  688. */
  689. void luaC_changemode (lua_State *L, int mode) {
  690. global_State *g = G(L);
  691. if (mode == g->gckind) return; /* nothing to change */
  692. if (mode == KGC_GEN) { /* change to generational mode */
  693. /* make sure gray lists are consistent */
  694. luaC_runtilstate(L, bitmask(GCSpropagate));
  695. g->lastmajormem = g->totalbytes;
  696. g->gckind = KGC_GEN;
  697. }
  698. else { /* change to incremental mode */
  699. /* sweep all objects to turn them back to white
  700. (as white has not changed, nothing extra will be collected) */
  701. g->sweepstrgc = 0;
  702. g->gcstate = GCSsweepstring;
  703. g->gckind = KGC_NORMAL;
  704. luaC_runtilstate(L, ~sweepphases);
  705. }
  706. }
  707. /*
  708. ** call all pending finalizers
  709. */
  710. static void callallpendingfinalizers (lua_State *L, int propagateerrors) {
  711. global_State *g = G(L);
  712. while (g->tobefnz) {
  713. resetoldbit(g->tobefnz);
  714. GCTM(L, propagateerrors);
  715. }
  716. }
  717. void luaC_freeallobjects (lua_State *L) {
  718. global_State *g = G(L);
  719. int i;
  720. callallpendingfinalizers(L, 0);
  721. /* following "white" makes all objects look dead */
  722. g->currentwhite = WHITEBITS;
  723. g->gckind = KGC_NORMAL;
  724. sweepwholelist(L, &g->finobj);
  725. lua_assert(g->finobj == NULL);
  726. sweepwholelist(L, &g->allgc);
  727. lua_assert(g->allgc == NULL);
  728. for (i = 0; i < g->strt.size; i++) /* free all string lists */
  729. sweepwholelist(L, &g->strt.hash[i]);
  730. lua_assert(g->strt.nuse == 0);
  731. }
  732. static void atomic (lua_State *L) {
  733. global_State *g = G(L);
  734. lua_assert(!iswhite(obj2gco(g->mainthread)));
  735. markobject(g, L); /* mark running thread */
  736. /* registry and global metatables may be changed by API */
  737. markvalue(g, &g->l_registry);
  738. markmt(g); /* mark basic metatables */
  739. /* remark occasional upvalues of (maybe) dead threads */
  740. remarkupvals(g);
  741. /* traverse objects caught by write barrier and by 'remarkupvals' */
  742. propagateall(g);
  743. traverselistofgrays(g, &g->weak); /* remark weak tables */
  744. traverselistofgrays(g, &g->ephemeron); /* remark ephemeron tables */
  745. traverselistofgrays(g, &g->grayagain); /* remark gray again */
  746. convergeephemerons(g);
  747. /* at this point, all strongly accessible objects are marked. */
  748. luaC_separateudata(L, 0); /* separate userdata to be finalized */
  749. markbeingfnz(g); /* mark userdata that will be finalized */
  750. propagateall(g); /* remark, to propagate `preserveness' */
  751. convergeephemerons(g);
  752. /* remove collected objects from weak tables */
  753. cleartable(g->weak);
  754. cleartable(g->ephemeron);
  755. cleartable(g->allweak);
  756. g->sweepstrgc = 0; /* prepare to sweep strings */
  757. g->gcstate = GCSsweepstring;
  758. g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
  759. /*lua_checkmemory(L);*/
  760. }
  761. static l_mem singlestep (lua_State *L) {
  762. global_State *g = G(L);
  763. switch (g->gcstate) {
  764. case GCSpause: {
  765. if (!isgenerational(g))
  766. markroot(L); /* start a new collection */
  767. /* in any case, root must be marked */
  768. lua_assert(!iswhite(obj2gco(g->mainthread))
  769. && !iswhite(gcvalue(&g->l_registry)));
  770. g->gcstate = GCSpropagate;
  771. return GCROOTCOST;
  772. }
  773. case GCSpropagate: {
  774. if (g->gray)
  775. return propagatemark(g);
  776. else { /* no more `gray' objects */
  777. g->gcstate = GCSatomic; /* finish mark phase */
  778. atomic(L);
  779. return GCATOMICCOST;
  780. }
  781. }
  782. case GCSsweepstring: {
  783. if (g->sweepstrgc < g->strt.size) {
  784. sweepwholelist(L, &g->strt.hash[g->sweepstrgc++]);
  785. return GCSWEEPCOST;
  786. }
  787. else { /* no more strings to sweep */
  788. g->sweepgc = &g->finobj; /* prepare to sweep finalizable objects */
  789. g->gcstate = GCSsweepudata;
  790. return 0;
  791. }
  792. }
  793. case GCSsweepudata: {
  794. if (*g->sweepgc) {
  795. g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
  796. return GCSWEEPMAX*GCSWEEPCOST;
  797. }
  798. else {
  799. g->sweepgc = &g->allgc; /* go to next phase */
  800. g->gcstate = GCSsweep;
  801. return GCSWEEPCOST;
  802. }
  803. }
  804. case GCSsweep: {
  805. if (*g->sweepgc) {
  806. g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
  807. return GCSWEEPMAX*GCSWEEPCOST;
  808. }
  809. else {
  810. /* sweep main thread */
  811. GCObject *mt = obj2gco(g->mainthread);
  812. sweeplist(L, &mt, 1);
  813. checkSizes(L);
  814. g->gcstate = GCSpause; /* finish collection */
  815. return GCSWEEPCOST;
  816. }
  817. }
  818. default: lua_assert(0); return 0;
  819. }
  820. }
  821. /*
  822. ** advances the garbage collector until it reaches a state allowed
  823. ** by 'statemask'
  824. */
  825. void luaC_runtilstate (lua_State *L, int statesmask) {
  826. global_State *g = G(L);
  827. while (!testbit(statesmask, g->gcstate))
  828. singlestep(L);
  829. }
  830. static void generationalcollection (lua_State *L) {
  831. global_State *g = G(L);
  832. if (g->lastmajormem == 0) { /* signal for another major collection? */
  833. luaC_fullgc(L, 0); /* perform a full regular collection */
  834. g->lastmajormem = g->totalbytes; /* update control */
  835. }
  836. else {
  837. luaC_runtilstate(L, ~bitmask(GCSpause)); /* run complete cycle */
  838. luaC_runtilstate(L, bitmask(GCSpause));
  839. if (g->totalbytes > g->lastmajormem/100 * g->gcmajorinc)
  840. g->lastmajormem = 0; /* signal for a major collection */
  841. }
  842. g->GCdebt = stddebt(g);
  843. }
  844. static void step (lua_State *L) {
  845. global_State *g = G(L);
  846. l_mem lim = g->gcstepmul; /* how much to work */
  847. do { /* always perform at least one single step */
  848. lim -= singlestep(L);
  849. } while (lim > 0 && g->gcstate != GCSpause);
  850. if (g->gcstate != GCSpause)
  851. g->GCdebt -= GCSTEPSIZE;
  852. else
  853. g->GCdebt = stddebt(g);
  854. }
  855. void luaC_step (lua_State *L) {
  856. int i;
  857. if (isgenerational(G(L))) generationalcollection(L);
  858. else step(L);
  859. for (i = 0; i < GCFINALIZENUM && G(L)->tobefnz; i++)
  860. GCTM(L, 1); /* Call a few pending finalizers */
  861. }
  862. /*
  863. ** performs a full GC cycle; if "isemergency", does not call
  864. ** finalizers (which could change stack positions)
  865. */
  866. void luaC_fullgc (lua_State *L, int isemergency) {
  867. global_State *g = G(L);
  868. int origkind = g->gckind;
  869. lua_assert(origkind != KGC_EMERGENCY);
  870. if (!isemergency) /* do not run finalizers during emergency GC */
  871. callallpendingfinalizers(L, 1);
  872. if (keepinvariant(g)) { /* marking phase? */
  873. /* must sweep all objects to turn them back to white
  874. (as white has not changed, nothing will be collected) */
  875. g->sweepstrgc = 0;
  876. g->gcstate = GCSsweepstring;
  877. }
  878. g->gckind = isemergency ? KGC_EMERGENCY : KGC_NORMAL;
  879. /* finish any pending sweep phase to start a new cycle */
  880. luaC_runtilstate(L, bitmask(GCSpause));
  881. /* run entire collector */
  882. luaC_runtilstate(L, ~bitmask(GCSpause));
  883. luaC_runtilstate(L, bitmask(GCSpause));
  884. if (origkind == KGC_GEN) { /* generational mode? */
  885. /* generational mode must always start in propagate phase */
  886. luaC_runtilstate(L, bitmask(GCSpropagate));
  887. }
  888. g->gckind = origkind;
  889. g->GCdebt = stddebt(g);
  890. if (!isemergency) /* do not run finalizers during emergency GC */
  891. callallpendingfinalizers(L, 1);
  892. }
  893. /* }====================================================== */