lgc.c 31 KB

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