lgc.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. /*
  2. ** $Id: lgc.c,v 1.170 2003/03/18 12:50:04 roberto Exp roberto $
  3. ** Garbage Collector
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <string.h>
  7. #define lgc_c
  8. #include "lua.h"
  9. #include "ldebug.h"
  10. #include "ldo.h"
  11. #include "lfunc.h"
  12. #include "lgc.h"
  13. #include "lmem.h"
  14. #include "lobject.h"
  15. #include "lstate.h"
  16. #include "lstring.h"
  17. #include "ltable.h"
  18. #include "ltm.h"
  19. typedef struct GCState {
  20. GCObject *tmark; /* list of marked objects to be traversed */
  21. GCObject *wk; /* list of traversed key-weak tables (to be cleared) */
  22. GCObject *wv; /* list of traversed value-weak tables */
  23. GCObject *wkv; /* list of traversed key-value weak tables */
  24. global_State *g;
  25. } GCState;
  26. /*
  27. ** some userful bit tricks
  28. */
  29. #define setbit(x,b) ((x) |= (1<<(b)))
  30. #define resetbit(x,b) ((x) &= cast(lu_byte, ~(1<<(b))))
  31. #define testbit(x,b) ((x) & (1<<(b)))
  32. #define unmark(x) resetbit((x)->gch.marked, 0)
  33. #define ismarked(x) ((x)->gch.marked & ((1<<4)|1))
  34. #define stringmark(s) setbit((s)->tsv.marked, 0)
  35. #define isfinalized(u) (!testbit((u)->uv.marked, 1))
  36. #define markfinalized(u) resetbit((u)->uv.marked, 1)
  37. #define KEYWEAKBIT 1
  38. #define VALUEWEAKBIT 2
  39. #define KEYWEAK (1<<KEYWEAKBIT)
  40. #define VALUEWEAK (1<<VALUEWEAKBIT)
  41. #define markobject(st,o) { checkconsistency(o); \
  42. if (iscollectable(o) && !ismarked(gcvalue(o))) reallymarkobject(st,gcvalue(o)); }
  43. #define condmarkobject(st,o,c) { checkconsistency(o); \
  44. if (iscollectable(o) && !ismarked(gcvalue(o)) && (c)) \
  45. reallymarkobject(st,gcvalue(o)); }
  46. #define markvalue(st,t) { if (!ismarked(valtogco(t))) \
  47. reallymarkobject(st, valtogco(t)); }
  48. static void reallymarkobject (GCState *st, GCObject *o) {
  49. lua_assert(!ismarked(o));
  50. setbit(o->gch.marked, 0); /* mark object */
  51. switch (o->gch.tt) {
  52. case LUA_TUSERDATA: {
  53. markvalue(st, gcotou(o)->uv.metatable);
  54. break;
  55. }
  56. case LUA_TFUNCTION: {
  57. gcotocl(o)->c.gclist = st->tmark;
  58. st->tmark = o;
  59. break;
  60. }
  61. case LUA_TTABLE: {
  62. gcotoh(o)->gclist = st->tmark;
  63. st->tmark = o;
  64. break;
  65. }
  66. case LUA_TTHREAD: {
  67. gcototh(o)->gclist = st->tmark;
  68. st->tmark = o;
  69. break;
  70. }
  71. case LUA_TPROTO: {
  72. gcotop(o)->gclist = st->tmark;
  73. st->tmark = o;
  74. break;
  75. }
  76. default: lua_assert(o->gch.tt == LUA_TSTRING);
  77. }
  78. }
  79. static void marktmu (GCState *st) {
  80. GCObject *u;
  81. for (u = st->g->tmudata; u; u = u->gch.next) {
  82. unmark(u); /* may be marked, if left from previous GC */
  83. reallymarkobject(st, u);
  84. }
  85. }
  86. /* move `dead' udata that need finalization to list `tmudata' */
  87. void luaC_separateudata (lua_State *L) {
  88. GCObject **p = &G(L)->rootudata;
  89. GCObject *curr;
  90. GCObject *collected = NULL; /* to collect udata with gc event */
  91. GCObject **lastcollected = &collected;
  92. while ((curr = *p) != NULL) {
  93. lua_assert(curr->gch.tt == LUA_TUSERDATA);
  94. if (ismarked(curr) || isfinalized(gcotou(curr)))
  95. p = &curr->gch.next; /* don't bother with them */
  96. else if (fasttm(L, gcotou(curr)->uv.metatable, TM_GC) == NULL) {
  97. markfinalized(gcotou(curr)); /* don't need finalization */
  98. p = &curr->gch.next;
  99. }
  100. else { /* must call its gc method */
  101. *p = curr->gch.next;
  102. curr->gch.next = NULL; /* link `curr' at the end of `collected' list */
  103. *lastcollected = curr;
  104. lastcollected = &curr->gch.next;
  105. }
  106. }
  107. /* insert collected udata with gc event into `tmudata' list */
  108. *lastcollected = G(L)->tmudata;
  109. G(L)->tmudata = collected;
  110. }
  111. static void removekey (Node *n) {
  112. setnilvalue(gval(n)); /* remove corresponding value ... */
  113. if (iscollectable(gkey(n)))
  114. setttype(gkey(n), LUA_TNONE); /* dead key; remove it */
  115. }
  116. static void traversetable (GCState *st, Table *h) {
  117. int i;
  118. int weakkey = 0;
  119. int weakvalue = 0;
  120. const TObject *mode;
  121. markvalue(st, h->metatable);
  122. lua_assert(h->lsizenode || h->node == st->g->dummynode);
  123. mode = gfasttm(st->g, h->metatable, TM_MODE);
  124. if (mode && ttisstring(mode)) { /* is there a weak mode? */
  125. weakkey = (strchr(svalue(mode), 'k') != NULL);
  126. weakvalue = (strchr(svalue(mode), 'v') != NULL);
  127. if (weakkey || weakvalue) { /* is really weak? */
  128. GCObject **weaklist;
  129. h->marked &= ~(KEYWEAK | VALUEWEAK); /* clear bits */
  130. h->marked |= cast(lu_byte, (weakkey << KEYWEAKBIT) |
  131. (weakvalue << VALUEWEAKBIT));
  132. weaklist = (weakkey && weakvalue) ? &st->wkv :
  133. (weakkey) ? &st->wk :
  134. &st->wv;
  135. h->gclist = *weaklist; /* must be cleared after GC, ... */
  136. *weaklist = valtogco(h); /* ... so put in the appropriate list */
  137. }
  138. }
  139. if (!weakvalue) {
  140. i = h->sizearray;
  141. while (i--)
  142. markobject(st, &h->array[i]);
  143. }
  144. i = sizenode(h);
  145. while (i--) {
  146. Node *n = gnode(h, i);
  147. if (!ttisnil(gval(n))) {
  148. lua_assert(!ttisnil(gkey(n)));
  149. condmarkobject(st, gkey(n), !weakkey);
  150. condmarkobject(st, gval(n), !weakvalue);
  151. }
  152. }
  153. }
  154. static void traverseproto (GCState *st, Proto *f) {
  155. int i;
  156. stringmark(f->source);
  157. for (i=0; i<f->sizek; i++) { /* mark literal strings */
  158. if (ttisstring(f->k+i))
  159. stringmark(tsvalue(f->k+i));
  160. }
  161. for (i=0; i<f->sizeupvalues; i++) /* mark upvalue names */
  162. stringmark(f->upvalues[i]);
  163. for (i=0; i<f->sizep; i++) /* mark nested protos */
  164. markvalue(st, f->p[i]);
  165. for (i=0; i<f->sizelocvars; i++) /* mark local-variable names */
  166. stringmark(f->locvars[i].varname);
  167. lua_assert(luaG_checkcode(f));
  168. }
  169. static void traverseclosure (GCState *st, Closure *cl) {
  170. if (cl->c.isC) {
  171. int i;
  172. for (i=0; i<cl->c.nupvalues; i++) /* mark its upvalues */
  173. markobject(st, &cl->c.upvalue[i]);
  174. }
  175. else {
  176. int i;
  177. lua_assert(cl->l.nupvalues == cl->l.p->nups);
  178. markvalue(st, hvalue(&cl->l.g));
  179. markvalue(st, cl->l.p);
  180. for (i=0; i<cl->l.nupvalues; i++) { /* mark its upvalues */
  181. UpVal *u = cl->l.upvals[i];
  182. if (!u->marked) {
  183. markobject(st, &u->value);
  184. u->marked = 1;
  185. }
  186. }
  187. }
  188. }
  189. static void checkstacksizes (lua_State *L, StkId max) {
  190. int used = L->ci - L->base_ci; /* number of `ci' in use */
  191. if (4*used < L->size_ci && 2*BASIC_CI_SIZE < L->size_ci)
  192. luaD_reallocCI(L, L->size_ci/2); /* still big enough... */
  193. else condhardstacktests(luaD_reallocCI(L, L->size_ci));
  194. used = max - L->stack; /* part of stack in use */
  195. if (4*used < L->stacksize && 2*(BASIC_STACK_SIZE+EXTRA_STACK) < L->stacksize)
  196. luaD_reallocstack(L, L->stacksize/2); /* still big enough... */
  197. else condhardstacktests(luaD_reallocstack(L, L->stacksize));
  198. }
  199. static void traversestack (GCState *st, lua_State *L1) {
  200. StkId o, lim;
  201. CallInfo *ci;
  202. markobject(st, gt(L1));
  203. lim = L1->top;
  204. for (ci = L1->base_ci; ci <= L1->ci; ci++) {
  205. lua_assert(ci->top <= L1->stack_last);
  206. lua_assert(ci->state & (CI_C | CI_HASFRAME | CI_SAVEDPC));
  207. if (!(ci->state & CI_C) && lim < ci->top)
  208. lim = ci->top;
  209. }
  210. for (o = L1->stack; o < L1->top; o++)
  211. markobject(st, o);
  212. for (; o <= lim; o++)
  213. setnilvalue(o);
  214. checkstacksizes(L1, lim);
  215. }
  216. static void propagatemarks (GCState *st) {
  217. while (st->tmark) { /* traverse marked objects */
  218. switch (st->tmark->gch.tt) {
  219. case LUA_TTABLE: {
  220. Table *h = gcotoh(st->tmark);
  221. st->tmark = h->gclist;
  222. traversetable(st, h);
  223. break;
  224. }
  225. case LUA_TFUNCTION: {
  226. Closure *cl = gcotocl(st->tmark);
  227. st->tmark = cl->c.gclist;
  228. traverseclosure(st, cl);
  229. break;
  230. }
  231. case LUA_TTHREAD: {
  232. lua_State *th = gcototh(st->tmark);
  233. st->tmark = th->gclist;
  234. traversestack(st, th);
  235. break;
  236. }
  237. case LUA_TPROTO: {
  238. Proto *p = gcotop(st->tmark);
  239. st->tmark = p->gclist;
  240. traverseproto(st, p);
  241. break;
  242. }
  243. default: lua_assert(0);
  244. }
  245. }
  246. }
  247. static int valismarked (const TObject *o) {
  248. if (ttisstring(o))
  249. stringmark(tsvalue(o)); /* strings are `values', so are never weak */
  250. return !iscollectable(o) || testbit(o->value.gc->gch.marked, 0);
  251. }
  252. /*
  253. ** clear collected keys from weaktables
  254. */
  255. static void cleartablekeys (GCObject *l) {
  256. while (l) {
  257. Table *h = gcotoh(l);
  258. int i = sizenode(h);
  259. lua_assert(h->marked & KEYWEAK);
  260. while (i--) {
  261. Node *n = gnode(h, i);
  262. if (!valismarked(gkey(n))) /* key was collected? */
  263. removekey(n); /* remove entry from table */
  264. }
  265. l = h->gclist;
  266. }
  267. }
  268. /*
  269. ** clear collected values from weaktables
  270. */
  271. static void cleartablevalues (GCObject *l) {
  272. while (l) {
  273. Table *h = gcotoh(l);
  274. int i = h->sizearray;
  275. lua_assert(h->marked & VALUEWEAK);
  276. while (i--) {
  277. TObject *o = &h->array[i];
  278. if (!valismarked(o)) /* value was collected? */
  279. setnilvalue(o); /* remove value */
  280. }
  281. i = sizenode(h);
  282. while (i--) {
  283. Node *n = gnode(h, i);
  284. if (!valismarked(gval(n))) /* value was collected? */
  285. removekey(n); /* remove entry from table */
  286. }
  287. l = h->gclist;
  288. }
  289. }
  290. static void freeobj (lua_State *L, GCObject *o) {
  291. switch (o->gch.tt) {
  292. case LUA_TPROTO: luaF_freeproto(L, gcotop(o)); break;
  293. case LUA_TFUNCTION: luaF_freeclosure(L, gcotocl(o)); break;
  294. case LUA_TUPVAL: luaM_freelem(L, gcotouv(o)); break;
  295. case LUA_TTABLE: luaH_free(L, gcotoh(o)); break;
  296. case LUA_TTHREAD: {
  297. lua_assert(gcototh(o) != L && gcototh(o) != G(L)->mainthread);
  298. luaE_freethread(L, gcototh(o));
  299. break;
  300. }
  301. case LUA_TSTRING: {
  302. luaM_free(L, o, sizestring(gcotots(o)->tsv.len));
  303. break;
  304. }
  305. case LUA_TUSERDATA: {
  306. luaM_free(L, o, sizeudata(gcotou(o)->uv.len));
  307. break;
  308. }
  309. default: lua_assert(0);
  310. }
  311. }
  312. static int sweeplist (lua_State *L, GCObject **p, int limit) {
  313. GCObject *curr;
  314. int count = 0; /* number of collected items */
  315. while ((curr = *p) != NULL) {
  316. if (curr->gch.marked > limit) {
  317. unmark(curr);
  318. p = &curr->gch.next;
  319. }
  320. else {
  321. count++;
  322. *p = curr->gch.next;
  323. freeobj(L, curr);
  324. }
  325. }
  326. return count;
  327. }
  328. static void sweepstrings (lua_State *L, int all) {
  329. int i;
  330. for (i=0; i<G(L)->strt.size; i++) { /* for each list */
  331. G(L)->strt.nuse -= sweeplist(L, &G(L)->strt.hash[i], all);
  332. }
  333. }
  334. static void checkSizes (lua_State *L) {
  335. /* check size of string hash */
  336. if (G(L)->strt.nuse < cast(ls_nstr, G(L)->strt.size/4) &&
  337. G(L)->strt.size > MINSTRTABSIZE*2)
  338. luaS_resize(L, G(L)->strt.size/2); /* table is too big */
  339. /* check size of buffer */
  340. if (luaZ_sizebuffer(&G(L)->buff) > LUA_MINBUFFER*2) { /* buffer too big? */
  341. size_t newsize = luaZ_sizebuffer(&G(L)->buff) / 2;
  342. luaZ_resizebuffer(L, &G(L)->buff, newsize);
  343. }
  344. G(L)->GCthreshold = 2*G(L)->nblocks; /* new threshold */
  345. }
  346. static void do1gcTM (lua_State *L, Udata *udata) {
  347. const TObject *tm = fasttm(L, udata->uv.metatable, TM_GC);
  348. if (tm != NULL) {
  349. setobj2s(L->top, tm);
  350. setuvalue(L->top+1, udata);
  351. L->top += 2;
  352. luaD_call(L, L->top - 2, 0);
  353. }
  354. }
  355. void luaC_callGCTM (lua_State *L) {
  356. lu_byte oldah = L->allowhook;
  357. L->allowhook = 0; /* stop debug hooks during GC tag methods */
  358. L->top++; /* reserve space to keep udata while runs its gc method */
  359. while (G(L)->tmudata != NULL) {
  360. GCObject *o = G(L)->tmudata;
  361. Udata *udata = gcotou(o);
  362. G(L)->tmudata = udata->uv.next; /* remove udata from `tmudata' */
  363. udata->uv.next = G(L)->rootudata; /* return it to `root' list */
  364. G(L)->rootudata = o;
  365. setuvalue(L->top - 1, udata); /* keep a reference to it */
  366. unmark(o);
  367. markfinalized(udata);
  368. do1gcTM(L, udata);
  369. }
  370. L->top--;
  371. L->allowhook = oldah; /* restore hooks */
  372. }
  373. void luaC_sweep (lua_State *L, int all) {
  374. if (all) all = 256; /* larger than any mark */
  375. sweeplist(L, &G(L)->rootudata, all);
  376. sweepstrings(L, all);
  377. sweeplist(L, &G(L)->rootgc, all);
  378. }
  379. /* mark root set */
  380. static void markroot (GCState *st, lua_State *L) {
  381. global_State *g = st->g;
  382. markobject(st, defaultmeta(L));
  383. markobject(st, registry(L));
  384. traversestack(st, g->mainthread);
  385. if (L != g->mainthread) /* another thread is running? */
  386. markvalue(st, L); /* cannot collect it */
  387. }
  388. static void mark (lua_State *L) {
  389. GCState st;
  390. GCObject *wkv;
  391. st.g = G(L);
  392. st.tmark = NULL;
  393. st.wkv = st.wk = st.wv = NULL;
  394. markroot(&st, L);
  395. propagatemarks(&st); /* mark all reachable objects */
  396. cleartablevalues(st.wkv);
  397. cleartablevalues(st.wv);
  398. wkv = st.wkv; /* keys must be cleared after preserving udata */
  399. st.wkv = NULL;
  400. st.wv = NULL;
  401. luaC_separateudata(L); /* separate userdata to be preserved */
  402. marktmu(&st); /* mark `preserved' userdata */
  403. propagatemarks(&st); /* remark, to propagate `preserveness' */
  404. cleartablekeys(wkv);
  405. /* `propagatemarks' may resuscitate some weak tables; clear them too */
  406. cleartablekeys(st.wk);
  407. cleartablevalues(st.wv);
  408. cleartablekeys(st.wkv);
  409. cleartablevalues(st.wkv);
  410. }
  411. void luaC_collectgarbage (lua_State *L) {
  412. mark(L);
  413. luaC_sweep(L, 0);
  414. checkSizes(L);
  415. luaC_callGCTM(L);
  416. }
  417. void luaC_link (lua_State *L, GCObject *o, lu_byte tt) {
  418. o->gch.next = G(L)->rootgc;
  419. G(L)->rootgc = o;
  420. o->gch.marked = 0;
  421. o->gch.tt = tt;
  422. }