lgc.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  1. /*
  2. ** $Id: lgc.c,v 2.107 2010/12/20 19:40:07 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 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 (global_State *g) {
  264. g->gray = g->grayagain = NULL;
  265. g->weak = g->allweak = g->ephemeron = NULL;
  266. markobject(g, g->mainthread);
  267. markvalue(g, &g->l_registry);
  268. markmt(g);
  269. markbeingfnz(g); /* mark any finalizing object left from previous cycle */
  270. }
  271. /* }====================================================== */
  272. /*
  273. ** {======================================================
  274. ** Traverse functions
  275. ** =======================================================
  276. */
  277. static void traverseweakvalue (global_State *g, Table *h) {
  278. Node *n, *limit = gnode(h, sizenode(h));
  279. for (n = gnode(h, 0); n < limit; n++) {
  280. checkdeadkey(n);
  281. if (ttisnil(gval(n))) /* entry is empty? */
  282. removeentry(n); /* remove it */
  283. else {
  284. lua_assert(!ttisnil(gkey(n)));
  285. markvalue(g, gkey(n)); /* mark key */
  286. }
  287. }
  288. linktable(h, &g->weak); /* link into appropriate list */
  289. }
  290. static int traverseephemeron (global_State *g, Table *h) {
  291. int marked = 0; /* true if an object is marked in this traversal */
  292. int hasclears = 0; /* true if table has unmarked pairs */
  293. Node *n, *limit = gnode(h, sizenode(h));
  294. int i;
  295. /* traverse array part (numeric keys are 'strong') */
  296. for (i = 0; i < h->sizearray; i++) {
  297. if (valiswhite(&h->array[i])) {
  298. marked = 1;
  299. reallymarkobject(g, gcvalue(&h->array[i]));
  300. }
  301. }
  302. /* traverse hash part */
  303. for (n = gnode(h, 0); n < limit; n++) {
  304. checkdeadkey(n);
  305. if (ttisnil(gval(n))) /* entry is empty? */
  306. removeentry(n); /* remove it */
  307. else if (valiswhite(gval(n))) { /* value not marked yet? */
  308. if (iscleared(gkey(n), 1)) /* key is not marked (yet)? */
  309. hasclears = 1; /* may have to propagate mark from key to value */
  310. else { /* key is marked, so mark value */
  311. marked = 1; /* value was not marked */
  312. reallymarkobject(g, gcvalue(gval(n)));
  313. }
  314. }
  315. }
  316. if (hasclears) /* does table have unmarked pairs? */
  317. linktable(h, &g->ephemeron); /* will have to propagate again */
  318. else /* nothing to propagate */
  319. linktable(h, &g->weak); /* avoid convergence phase */
  320. return marked;
  321. }
  322. static void traversestrongtable (global_State *g, Table *h) {
  323. Node *n, *limit = gnode(h, sizenode(h));
  324. int i;
  325. for (i = 0; i < h->sizearray; i++) /* traverse array part */
  326. markvalue(g, &h->array[i]);
  327. for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
  328. checkdeadkey(n);
  329. if (ttisnil(gval(n))) /* entry is empty? */
  330. removeentry(n); /* remove it */
  331. else {
  332. lua_assert(!ttisnil(gkey(n)));
  333. markvalue(g, gkey(n)); /* mark key */
  334. markvalue(g, gval(n)); /* mark value */
  335. }
  336. }
  337. }
  338. static int traversetable (global_State *g, Table *h) {
  339. const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
  340. markobject(g, h->metatable);
  341. if (mode && ttisstring(mode)) { /* is there a weak mode? */
  342. int weakkey = (strchr(svalue(mode), 'k') != NULL);
  343. int weakvalue = (strchr(svalue(mode), 'v') != NULL);
  344. if (weakkey || weakvalue) { /* is really weak? */
  345. black2gray(obj2gco(h)); /* keep table gray */
  346. if (!weakkey) { /* strong keys? */
  347. traverseweakvalue(g, h);
  348. return TRAVCOST + sizenode(h);
  349. }
  350. else if (!weakvalue) { /* strong values? */
  351. traverseephemeron(g, h);
  352. return TRAVCOST + h->sizearray + sizenode(h);
  353. }
  354. else {
  355. linktable(h, &g->allweak); /* nothing to traverse now */
  356. return TRAVCOST;
  357. }
  358. } /* else go through */
  359. }
  360. traversestrongtable(g, h);
  361. return TRAVCOST + h->sizearray + (2 * sizenode(h));
  362. }
  363. static int traverseproto (global_State *g, Proto *f) {
  364. int i;
  365. if (f->cache && iswhite(obj2gco(f->cache)))
  366. f->cache = NULL; /* allow cache to be collected */
  367. stringmark(f->source);
  368. for (i = 0; i < f->sizek; i++) /* mark literals */
  369. markvalue(g, &f->k[i]);
  370. for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
  371. stringmark(f->upvalues[i].name);
  372. for (i = 0; i < f->sizep; i++) /* mark nested protos */
  373. markobject(g, f->p[i]);
  374. for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
  375. stringmark(f->locvars[i].varname);
  376. return TRAVCOST + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars;
  377. }
  378. static int traverseclosure (global_State *g, Closure *cl) {
  379. if (cl->c.isC) {
  380. int i;
  381. for (i=0; i<cl->c.nupvalues; i++) /* mark its upvalues */
  382. markvalue(g, &cl->c.upvalue[i]);
  383. }
  384. else {
  385. int i;
  386. lua_assert(cl->l.nupvalues == cl->l.p->sizeupvalues);
  387. markobject(g, cl->l.p); /* mark its prototype */
  388. for (i=0; i<cl->l.nupvalues; i++) /* mark its upvalues */
  389. markobject(g, cl->l.upvals[i]);
  390. }
  391. return TRAVCOST + cl->c.nupvalues;
  392. }
  393. static int traversestack (global_State *g, lua_State *L) {
  394. StkId o = L->stack;
  395. if (o == NULL)
  396. return 1; /* stack not completely built yet */
  397. for (; o < L->top; o++)
  398. markvalue(g, o);
  399. if (g->gcstate == GCSatomic) { /* final traversal? */
  400. StkId lim = L->stack + L->stacksize; /* real end of stack */
  401. for (; o < lim; o++) /* clear not-marked stack slice */
  402. setnilvalue(o);
  403. }
  404. return TRAVCOST + cast_int(o - L->stack);
  405. }
  406. /*
  407. ** traverse one gray object, turning it to black (except for threads,
  408. ** which are always gray).
  409. ** Returns number of values traversed.
  410. */
  411. static int propagatemark (global_State *g) {
  412. GCObject *o = g->gray;
  413. lua_assert(isgray(o));
  414. gray2black(o);
  415. switch (gch(o)->tt) {
  416. case LUA_TTABLE: {
  417. Table *h = gco2t(o);
  418. g->gray = h->gclist;
  419. return traversetable(g, h);
  420. }
  421. case LUA_TFUNCTION: {
  422. Closure *cl = gco2cl(o);
  423. g->gray = cl->c.gclist;
  424. return traverseclosure(g, cl);
  425. }
  426. case LUA_TTHREAD: {
  427. lua_State *th = gco2th(o);
  428. g->gray = th->gclist;
  429. th->gclist = g->grayagain;
  430. g->grayagain = o;
  431. black2gray(o);
  432. return traversestack(g, th);
  433. }
  434. case LUA_TPROTO: {
  435. Proto *p = gco2p(o);
  436. g->gray = p->gclist;
  437. return traverseproto(g, p);
  438. }
  439. default: lua_assert(0); return 0;
  440. }
  441. }
  442. static void propagateall (global_State *g) {
  443. while (g->gray) propagatemark(g);
  444. }
  445. static void traverselistofgrays (global_State *g, GCObject **l) {
  446. lua_assert(g->gray == NULL); /* no grays left */
  447. g->gray = *l; /* now 'l' is new gray list */
  448. *l = NULL;
  449. propagateall(g);
  450. }
  451. static void convergeephemerons (global_State *g) {
  452. int changed;
  453. do {
  454. GCObject *w;
  455. GCObject *next = g->ephemeron; /* get ephemeron list */
  456. g->ephemeron = NULL; /* tables will return to this list when traversed */
  457. changed = 0;
  458. while ((w = next) != NULL) {
  459. next = gco2t(w)->gclist;
  460. if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */
  461. propagateall(g); /* propagate changes */
  462. changed = 1; /* will have to revisit all ephemeron tables */
  463. }
  464. }
  465. } while (changed);
  466. }
  467. /* }====================================================== */
  468. /*
  469. ** {======================================================
  470. ** Sweep Functions
  471. ** =======================================================
  472. */
  473. /*
  474. ** clear collected entries from all weaktables in list 'l'
  475. */
  476. static void cleartable (GCObject *l) {
  477. for (; l != NULL; l = gco2t(l)->gclist) {
  478. Table *h = gco2t(l);
  479. Node *n, *limit = gnode(h, sizenode(h));
  480. int i;
  481. for (i = 0; i < h->sizearray; i++) {
  482. TValue *o = &h->array[i];
  483. if (iscleared(o, 0)) /* value was collected? */
  484. setnilvalue(o); /* remove value */
  485. }
  486. for (n = gnode(h, 0); n < limit; n++) {
  487. if (!ttisnil(gval(n)) && /* non-empty entry? */
  488. (iscleared(gkey(n), 1) || iscleared(gval(n), 0))) {
  489. setnilvalue(gval(n)); /* remove value ... */
  490. removeentry(n); /* and remove entry from table */
  491. }
  492. }
  493. }
  494. }
  495. static void freeobj (lua_State *L, GCObject *o) {
  496. switch (gch(o)->tt) {
  497. case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
  498. case LUA_TFUNCTION: luaF_freeclosure(L, gco2cl(o)); break;
  499. case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break;
  500. case LUA_TTABLE: luaH_free(L, gco2t(o)); break;
  501. case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
  502. case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
  503. case LUA_TSTRING: {
  504. G(L)->strt.nuse--;
  505. luaM_freemem(L, o, sizestring(gco2ts(o)));
  506. break;
  507. }
  508. default: lua_assert(0);
  509. }
  510. }
  511. #define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM)
  512. static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);
  513. /*
  514. ** sweep the (open) upvalues of a thread and resize its stack and
  515. ** list of call-info structures.
  516. */
  517. static void sweepthread (lua_State *L, lua_State *L1) {
  518. if (L1->stack == NULL) return; /* stack not completely built yet */
  519. sweepwholelist(L, &L1->openupval); /* sweep open upvalues */
  520. luaE_freeCI(L1); /* free extra CallInfo slots */
  521. /* should not change the stack during an emergency gc cycle */
  522. if (G(L)->gckind != KGC_EMERGENCY)
  523. luaD_shrinkstack(L1);
  524. }
  525. /*
  526. ** sweep at most 'count' elements from a list of GCObjects erasing dead
  527. ** objects, where a dead (not alive) object is one marked with the "old"
  528. ** (non current) white and not fixed.
  529. ** In non-generational mode, change all non-dead objects back to white,
  530. ** preparing for next collection cycle.
  531. ** In generational mode, keep black objects black, and also mark them as
  532. ** old; stop when hitting an old object, as all objects after that
  533. ** one will be old too.
  534. ** When object is a thread, sweep its list of open upvalues too.
  535. */
  536. static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
  537. global_State *g = G(L);
  538. int ow = otherwhite(g);
  539. int toclear, toset; /* bits to clear and to set in all live objects */
  540. int tostop; /* stop sweep when this is true */
  541. l_mem debt = g->GCdebt; /* current debt */
  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. p = &nullp; /* stop sweeping this list */
  565. break;
  566. }
  567. /* update marks */
  568. gch(curr)->marked = cast_byte((marked & toclear) | toset);
  569. p = &gch(curr)->next; /* go to next element */
  570. }
  571. }
  572. luaE_setdebt(g, debt); /* sweeping should not change debt */
  573. return p;
  574. }
  575. /* }====================================================== */
  576. /*
  577. ** {======================================================
  578. ** Finalization
  579. ** =======================================================
  580. */
  581. static void checkSizes (lua_State *L) {
  582. global_State *g = G(L);
  583. if (g->gckind != KGC_EMERGENCY) { /* do not change sizes in emergency */
  584. int hs = g->strt.size / 2; /* half the size of the string table */
  585. if (g->strt.nuse < cast(lu_int32, hs)) /* using less than that half? */
  586. luaS_resize(L, hs); /* halve its size */
  587. luaZ_freebuffer(L, &g->buff); /* free concatenation buffer */
  588. }
  589. }
  590. static GCObject *udata2finalize (global_State *g) {
  591. GCObject *o = g->tobefnz; /* get first element */
  592. lua_assert(isfinalized(o));
  593. g->tobefnz = gch(o)->next; /* remove it from 'tobefnz' list */
  594. gch(o)->next = g->allgc; /* return it to 'allgc' list */
  595. g->allgc = o;
  596. resetbit(gch(o)->marked, SEPARATED); /* mark that it is not in 'tobefnz' */
  597. lua_assert(!isold(o)); /* see MOVE OLD rule */
  598. if (!keepinvariant(g)) /* not keeping invariant? */
  599. makewhite(g, o); /* "sweep" object */
  600. return o;
  601. }
  602. static void dothecall (lua_State *L, void *ud) {
  603. UNUSED(ud);
  604. luaD_call(L, L->top - 2, 0, 0);
  605. }
  606. static void GCTM (lua_State *L, int propagateerrors) {
  607. global_State *g = G(L);
  608. const TValue *tm;
  609. TValue v;
  610. setgcovalue(L, &v, udata2finalize(g));
  611. tm = luaT_gettmbyobj(L, &v, TM_GC);
  612. if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */
  613. int status;
  614. lu_byte oldah = L->allowhook;
  615. int running = g->gcrunning;
  616. L->allowhook = 0; /* stop debug hooks during GC tag method */
  617. g->gcrunning = 0; /* avoid GC steps */
  618. setobj2s(L, L->top, tm); /* push finalizer... */
  619. setobj2s(L, L->top + 1, &v); /* ... and its argument */
  620. L->top += 2; /* and (next line) call the finalizer */
  621. status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
  622. L->allowhook = oldah; /* restore hooks */
  623. g->gcrunning = running; /* restore state */
  624. if (status != LUA_OK && propagateerrors) { /* error while running __gc? */
  625. if (status == LUA_ERRRUN) { /* is there an error msg.? */
  626. luaO_pushfstring(L, "error in __gc tag method (%s)",
  627. lua_tostring(L, -1));
  628. status = LUA_ERRGCMM; /* error in __gc metamethod */
  629. }
  630. luaD_throw(L, status); /* re-send error */
  631. }
  632. }
  633. }
  634. /*
  635. ** move all unreachable objects that need finalization from list 'finobj'
  636. ** to list 'tobefnz'
  637. */
  638. void luaC_separateudata (lua_State *L, int all) {
  639. global_State *g = G(L);
  640. GCObject **p = &g->finobj;
  641. GCObject *curr;
  642. GCObject **lastnext = &g->tobefnz;
  643. /* find last 'next' field in 'tobefnz' list (to add elements in its end) */
  644. while (*lastnext != NULL)
  645. lastnext = &gch(*lastnext)->next;
  646. while ((curr = *p) != NULL) { /* traverse all finalizable objects */
  647. lua_assert(!isfinalized(curr));
  648. lua_assert(testbit(gch(curr)->marked, SEPARATED));
  649. if (!(all || iswhite(curr))) /* not being collected? */
  650. p = &gch(curr)->next; /* don't bother with it */
  651. else {
  652. l_setbit(gch(curr)->marked, FINALIZEDBIT); /* won't be finalized again */
  653. *p = gch(curr)->next; /* remove 'curr' from 'finobj' list */
  654. gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */
  655. *lastnext = curr;
  656. lastnext = &gch(curr)->next;
  657. }
  658. }
  659. }
  660. /*
  661. ** if object 'o' has a finalizer, remove it from 'allgc' list (must
  662. ** search the list to find it) and link it in 'finobj' list.
  663. */
  664. void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
  665. global_State *g = G(L);
  666. if (testbit(gch(o)->marked, SEPARATED) || /* obj. is already separated... */
  667. isfinalized(o) || /* ... or is finalized... */
  668. gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */
  669. return; /* nothing to be done */
  670. else { /* move 'o' to 'finobj' list */
  671. GCObject **p;
  672. for (p = &g->allgc; *p != o; p = &gch(*p)->next) ;
  673. *p = gch(o)->next; /* remove 'o' from root list */
  674. gch(o)->next = g->finobj; /* link it in list 'finobj' */
  675. g->finobj = o;
  676. l_setbit(gch(o)->marked, SEPARATED); /* mark it as such */
  677. resetoldbit(o); /* see MOVE OLD rule */
  678. }
  679. }
  680. /* }====================================================== */
  681. /*
  682. ** {======================================================
  683. ** GC control
  684. ** =======================================================
  685. */
  686. #define sweepphases \
  687. (bitmask(GCSsweepstring) | bitmask(GCSsweepudata) | bitmask(GCSsweep))
  688. /*
  689. ** change GC mode
  690. */
  691. void luaC_changemode (lua_State *L, int mode) {
  692. global_State *g = G(L);
  693. if (mode == g->gckind) return; /* nothing to change */
  694. if (mode == KGC_GEN) { /* change to generational mode */
  695. /* make sure gray lists are consistent */
  696. luaC_runtilstate(L, bitmask(GCSpropagate));
  697. g->lastmajormem = gettotalbytes(g);
  698. g->gckind = KGC_GEN;
  699. }
  700. else { /* change to incremental mode */
  701. /* sweep all objects to turn them back to white
  702. (as white has not changed, nothing extra will be collected) */
  703. g->sweepstrgc = 0;
  704. g->gcstate = GCSsweepstring;
  705. g->gckind = KGC_NORMAL;
  706. luaC_runtilstate(L, ~sweepphases);
  707. }
  708. }
  709. /*
  710. ** call all pending finalizers
  711. */
  712. static void callallpendingfinalizers (lua_State *L, int propagateerrors) {
  713. global_State *g = G(L);
  714. while (g->tobefnz) {
  715. resetoldbit(g->tobefnz);
  716. GCTM(L, propagateerrors);
  717. }
  718. }
  719. void luaC_freeallobjects (lua_State *L) {
  720. global_State *g = G(L);
  721. int i;
  722. callallpendingfinalizers(L, 0);
  723. /* following "white" makes all objects look dead */
  724. g->currentwhite = WHITEBITS;
  725. g->gckind = KGC_NORMAL;
  726. sweepwholelist(L, &g->finobj);
  727. lua_assert(g->finobj == NULL);
  728. sweepwholelist(L, &g->allgc);
  729. lua_assert(g->allgc == NULL);
  730. for (i = 0; i < g->strt.size; i++) /* free all string lists */
  731. sweepwholelist(L, &g->strt.hash[i]);
  732. lua_assert(g->strt.nuse == 0);
  733. }
  734. static void atomic (lua_State *L) {
  735. global_State *g = G(L);
  736. lua_assert(!iswhite(obj2gco(g->mainthread)));
  737. markobject(g, L); /* mark running thread */
  738. /* registry and global metatables may be changed by API */
  739. markvalue(g, &g->l_registry);
  740. markmt(g); /* mark basic metatables */
  741. /* remark occasional upvalues of (maybe) dead threads */
  742. remarkupvals(g);
  743. /* traverse objects caught by write barrier and by 'remarkupvals' */
  744. propagateall(g);
  745. traverselistofgrays(g, &g->weak); /* remark weak tables */
  746. traverselistofgrays(g, &g->ephemeron); /* remark ephemeron tables */
  747. traverselistofgrays(g, &g->grayagain); /* remark gray again */
  748. convergeephemerons(g);
  749. /* at this point, all strongly accessible objects are marked. */
  750. luaC_separateudata(L, 0); /* separate userdata to be finalized */
  751. markbeingfnz(g); /* mark userdata that will be finalized */
  752. propagateall(g); /* remark, to propagate `preserveness' */
  753. convergeephemerons(g);
  754. /* remove collected objects from weak tables */
  755. cleartable(g->weak);
  756. cleartable(g->ephemeron);
  757. cleartable(g->allweak);
  758. g->sweepstrgc = 0; /* prepare to sweep strings */
  759. g->gcstate = GCSsweepstring;
  760. g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
  761. /*lua_checkmemory(L);*/
  762. }
  763. static l_mem singlestep (lua_State *L) {
  764. global_State *g = G(L);
  765. switch (g->gcstate) {
  766. case GCSpause: {
  767. if (!isgenerational(g))
  768. markroot(g); /* start a new collection */
  769. /* in any case, root must be marked */
  770. lua_assert(!iswhite(obj2gco(g->mainthread))
  771. && !iswhite(gcvalue(&g->l_registry)));
  772. g->gcstate = GCSpropagate;
  773. return GCROOTCOST;
  774. }
  775. case GCSpropagate: {
  776. if (g->gray)
  777. return propagatemark(g);
  778. else { /* no more `gray' objects */
  779. g->gcstate = GCSatomic; /* finish mark phase */
  780. atomic(L);
  781. return GCATOMICCOST;
  782. }
  783. }
  784. case GCSsweepstring: {
  785. if (g->sweepstrgc < g->strt.size) {
  786. sweepwholelist(L, &g->strt.hash[g->sweepstrgc++]);
  787. return GCSWEEPCOST;
  788. }
  789. else { /* no more strings to sweep */
  790. g->sweepgc = &g->finobj; /* prepare to sweep finalizable objects */
  791. g->gcstate = GCSsweepudata;
  792. return 0;
  793. }
  794. }
  795. case GCSsweepudata: {
  796. if (*g->sweepgc) {
  797. g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
  798. return GCSWEEPMAX*GCSWEEPCOST;
  799. }
  800. else {
  801. g->sweepgc = &g->allgc; /* go to next phase */
  802. g->gcstate = GCSsweep;
  803. return GCSWEEPCOST;
  804. }
  805. }
  806. case GCSsweep: {
  807. if (*g->sweepgc) {
  808. g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
  809. return GCSWEEPMAX*GCSWEEPCOST;
  810. }
  811. else {
  812. /* sweep main thread */
  813. GCObject *mt = obj2gco(g->mainthread);
  814. sweeplist(L, &mt, 1);
  815. checkSizes(L);
  816. g->gcstate = GCSpause; /* finish collection */
  817. return GCSWEEPCOST;
  818. }
  819. }
  820. default: lua_assert(0); return 0;
  821. }
  822. }
  823. /*
  824. ** advances the garbage collector until it reaches a state allowed
  825. ** by 'statemask'
  826. */
  827. void luaC_runtilstate (lua_State *L, int statesmask) {
  828. global_State *g = G(L);
  829. while (!testbit(statesmask, g->gcstate))
  830. singlestep(L);
  831. }
  832. static void generationalcollection (lua_State *L) {
  833. global_State *g = G(L);
  834. if (g->lastmajormem == 0) { /* signal for another major collection? */
  835. luaC_fullgc(L, 0); /* perform a full regular collection */
  836. g->lastmajormem = gettotalbytes(g); /* update control */
  837. }
  838. else {
  839. luaC_runtilstate(L, ~bitmask(GCSpause)); /* run complete cycle */
  840. luaC_runtilstate(L, bitmask(GCSpause));
  841. if (gettotalbytes(g) > g->lastmajormem/100 * g->gcmajorinc)
  842. g->lastmajormem = 0; /* signal for a major collection */
  843. }
  844. luaE_setdebt(g, stddebt(g));
  845. }
  846. static void step (lua_State *L) {
  847. global_State *g = G(L);
  848. l_mem lim = g->gcstepmul; /* how much to work */
  849. do { /* always perform at least one single step */
  850. lim -= singlestep(L);
  851. } while (lim > 0 && g->gcstate != GCSpause);
  852. if (g->gcstate != GCSpause)
  853. luaE_setdebt(g, g->GCdebt - GCSTEPSIZE);
  854. else
  855. luaE_setdebt(g, stddebt(g));
  856. }
  857. /*
  858. ** performs a basic GC step even if the collector is stopped
  859. */
  860. void luaC_forcestep (lua_State *L) {
  861. global_State *g = G(L);
  862. int i;
  863. if (isgenerational(g)) generationalcollection(L);
  864. else step(L);
  865. for (i = 0; i < GCFINALIZENUM && g->tobefnz; i++)
  866. GCTM(L, 1); /* Call a few pending finalizers */
  867. }
  868. /*
  869. ** performs a basic GC step only if collector is running
  870. */
  871. void luaC_step (lua_State *L) {
  872. if (G(L)->gcrunning) luaC_forcestep(L);
  873. }
  874. /*
  875. ** performs a full GC cycle; if "isemergency", does not call
  876. ** finalizers (which could change stack positions)
  877. */
  878. void luaC_fullgc (lua_State *L, int isemergency) {
  879. global_State *g = G(L);
  880. int origkind = g->gckind;
  881. lua_assert(origkind != KGC_EMERGENCY);
  882. if (!isemergency) /* do not run finalizers during emergency GC */
  883. callallpendingfinalizers(L, 1);
  884. if (keepinvariant(g)) { /* marking phase? */
  885. /* must sweep all objects to turn them back to white
  886. (as white has not changed, nothing will be collected) */
  887. g->sweepstrgc = 0;
  888. g->gcstate = GCSsweepstring;
  889. }
  890. g->gckind = isemergency ? KGC_EMERGENCY : KGC_NORMAL;
  891. /* finish any pending sweep phase to start a new cycle */
  892. luaC_runtilstate(L, bitmask(GCSpause));
  893. /* run entire collector */
  894. luaC_runtilstate(L, ~bitmask(GCSpause));
  895. luaC_runtilstate(L, bitmask(GCSpause));
  896. if (origkind == KGC_GEN) { /* generational mode? */
  897. /* generational mode must always start in propagate phase */
  898. luaC_runtilstate(L, bitmask(GCSpropagate));
  899. }
  900. g->gckind = origkind;
  901. luaE_setdebt(g, stddebt(g));
  902. if (!isemergency) /* do not run finalizers during emergency GC */
  903. callallpendingfinalizers(L, 1);
  904. }
  905. /* }====================================================== */