lgc.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. /*
  2. ** $Id: lgc.c,v 1.165 2002/12/02 12:06:10 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. static void 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(val(n)); /* remove corresponding value ... */
  113. if (iscollectable(key(n)))
  114. setttype(key(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 |= (weakkey << KEYWEAKBIT) | (weakvalue << VALUEWEAKBIT);
  131. weaklist = (weakkey && weakvalue) ? &st->wkv :
  132. (weakkey) ? &st->wk :
  133. &st->wv;
  134. h->gclist = *weaklist; /* must be cleared after GC, ... */
  135. *weaklist = valtogco(h); /* ... so put in the appropriate list */
  136. }
  137. }
  138. if (!weakvalue) {
  139. i = sizearray(h);
  140. while (i--)
  141. markobject(st, &h->array[i]);
  142. }
  143. i = sizenode(h);
  144. while (i--) {
  145. Node *n = node(h, i);
  146. if (!ttisnil(val(n))) {
  147. lua_assert(!ttisnil(key(n)));
  148. condmarkobject(st, key(n), !weakkey);
  149. condmarkobject(st, val(n), !weakvalue);
  150. }
  151. }
  152. }
  153. static void traverseproto (GCState *st, Proto *f) {
  154. int i;
  155. stringmark(f->source);
  156. for (i=0; i<f->sizek; i++) {
  157. if (ttisstring(f->k+i))
  158. stringmark(tsvalue(f->k+i));
  159. }
  160. for (i=0; i<f->sizep; i++)
  161. markvalue(st, f->p[i]);
  162. for (i=0; i<f->sizelocvars; i++) /* mark local-variable names */
  163. stringmark(f->locvars[i].varname);
  164. lua_assert(luaG_checkcode(f));
  165. }
  166. static void traverseclosure (GCState *st, Closure *cl) {
  167. if (cl->c.isC) {
  168. int i;
  169. for (i=0; i<cl->c.nupvalues; i++) /* mark its upvalues */
  170. markobject(st, &cl->c.upvalue[i]);
  171. }
  172. else {
  173. int i;
  174. lua_assert(cl->l.nupvalues == cl->l.p->nupvalues);
  175. markvalue(st, hvalue(&cl->l.g));
  176. markvalue(st, cl->l.p);
  177. for (i=0; i<cl->l.nupvalues; i++) { /* mark its upvalues */
  178. UpVal *u = cl->l.upvals[i];
  179. if (!u->marked) {
  180. markobject(st, &u->value);
  181. u->marked = 1;
  182. }
  183. }
  184. }
  185. }
  186. static void checkstacksizes (lua_State *L, StkId max) {
  187. int used = L->ci - L->base_ci; /* number of `ci' in use */
  188. if (4*used < L->size_ci && 2*BASIC_CI_SIZE < L->size_ci)
  189. luaD_reallocCI(L, L->size_ci/2); /* still big enough... */
  190. else condhardstacktests(luaD_reallocCI(L, L->size_ci));
  191. used = max - L->stack; /* part of stack in use */
  192. if (4*used < L->stacksize && 2*(BASIC_STACK_SIZE+EXTRA_STACK) < L->stacksize)
  193. luaD_reallocstack(L, L->stacksize/2); /* still big enough... */
  194. else condhardstacktests(luaD_reallocstack(L, L->stacksize));
  195. }
  196. static void traversestack (GCState *st, lua_State *L1) {
  197. StkId o, lim;
  198. CallInfo *ci;
  199. markobject(st, gt(L1));
  200. lim = L1->top;
  201. for (ci = L1->base_ci; ci <= L1->ci; ci++) {
  202. lua_assert(ci->top <= L1->stack_last);
  203. lua_assert(ci->state & (CI_C | CI_HASFRAME | CI_SAVEDPC));
  204. if (!(ci->state & CI_C) && lim < ci->top)
  205. lim = ci->top;
  206. }
  207. for (o = L1->stack; o < L1->top; o++)
  208. markobject(st, o);
  209. for (; o <= lim; o++)
  210. setnilvalue(o);
  211. checkstacksizes(L1, lim);
  212. }
  213. static void propagatemarks (GCState *st) {
  214. while (st->tmark) { /* traverse marked objects */
  215. switch (st->tmark->gch.tt) {
  216. case LUA_TTABLE: {
  217. Table *h = gcotoh(st->tmark);
  218. st->tmark = h->gclist;
  219. traversetable(st, h);
  220. break;
  221. }
  222. case LUA_TFUNCTION: {
  223. Closure *cl = gcotocl(st->tmark);
  224. st->tmark = cl->c.gclist;
  225. traverseclosure(st, cl);
  226. break;
  227. }
  228. case LUA_TTHREAD: {
  229. lua_State *th = gcototh(st->tmark);
  230. st->tmark = th->gclist;
  231. traversestack(st, th);
  232. break;
  233. }
  234. case LUA_TPROTO: {
  235. Proto *p = gcotop(st->tmark);
  236. st->tmark = p->gclist;
  237. traverseproto(st, p);
  238. break;
  239. }
  240. default: lua_assert(0);
  241. }
  242. }
  243. }
  244. static int valismarked (const TObject *o) {
  245. if (ttisstring(o))
  246. stringmark(tsvalue(o)); /* strings are `values', so are never weak */
  247. return !iscollectable(o) || testbit(o->value.gc->gch.marked, 0);
  248. }
  249. /*
  250. ** clear collected keys from weaktables
  251. */
  252. static void cleartablekeys (GCObject *l) {
  253. while (l) {
  254. Table *h = gcotoh(l);
  255. int i = sizenode(h);
  256. lua_assert(h->marked & KEYWEAK);
  257. while (i--) {
  258. Node *n = node(h, i);
  259. if (!valismarked(key(n))) /* key was collected? */
  260. removekey(n); /* remove entry from table */
  261. }
  262. l = h->gclist;
  263. }
  264. }
  265. /*
  266. ** clear collected values from weaktables
  267. */
  268. static void cleartablevalues (GCObject *l) {
  269. while (l) {
  270. Table *h = gcotoh(l);
  271. int i = sizearray(h);
  272. lua_assert(h->marked & VALUEWEAK);
  273. while (i--) {
  274. TObject *o = &h->array[i];
  275. if (!valismarked(o)) /* value was collected? */
  276. setnilvalue(o); /* remove value */
  277. }
  278. i = sizenode(h);
  279. while (i--) {
  280. Node *n = node(h, i);
  281. if (!valismarked(val(n))) /* value was collected? */
  282. removekey(n); /* remove entry from table */
  283. }
  284. l = h->gclist;
  285. }
  286. }
  287. static void freeobj (lua_State *L, GCObject *o) {
  288. switch (o->gch.tt) {
  289. case LUA_TPROTO: luaF_freeproto(L, gcotop(o)); break;
  290. case LUA_TFUNCTION: luaF_freeclosure(L, gcotocl(o)); break;
  291. case LUA_TUPVAL: luaM_freelem(L, gcotouv(o)); break;
  292. case LUA_TTABLE: luaH_free(L, gcotoh(o)); break;
  293. case LUA_TTHREAD: {
  294. lua_assert(gcototh(o) != L && gcototh(o) != G(L)->mainthread);
  295. luaE_freethread(L, gcototh(o));
  296. break;
  297. }
  298. case LUA_TSTRING: {
  299. luaM_free(L, o, sizestring(gcotots(o)->tsv.len));
  300. break;
  301. }
  302. case LUA_TUSERDATA: {
  303. luaM_free(L, o, sizeudata(gcotou(o)->uv.len));
  304. break;
  305. }
  306. default: lua_assert(0);
  307. }
  308. }
  309. static int sweeplist (lua_State *L, GCObject **p, int limit) {
  310. GCObject *curr;
  311. int count = 0; /* number of collected items */
  312. while ((curr = *p) != NULL) {
  313. if (curr->gch.marked > limit) {
  314. unmark(curr);
  315. p = &curr->gch.next;
  316. }
  317. else {
  318. count++;
  319. *p = curr->gch.next;
  320. freeobj(L, curr);
  321. }
  322. }
  323. return count;
  324. }
  325. static void sweepstrings (lua_State *L, int all) {
  326. int i;
  327. for (i=0; i<G(L)->strt.size; i++) { /* for each list */
  328. G(L)->strt.nuse -= sweeplist(L, &G(L)->strt.hash[i], all);
  329. }
  330. }
  331. static void checkSizes (lua_State *L) {
  332. /* check size of string hash */
  333. if (G(L)->strt.nuse < cast(ls_nstr, G(L)->strt.size/4) &&
  334. G(L)->strt.size > MINSTRTABSIZE*2)
  335. luaS_resize(L, G(L)->strt.size/2); /* table is too big */
  336. /* check size of buffer */
  337. if (luaZ_sizebuffer(&G(L)->buff) > LUA_MINBUFFER*2) { /* buffer too big? */
  338. size_t newsize = luaZ_sizebuffer(&G(L)->buff) / 2;
  339. luaZ_resizebuffer(L, &G(L)->buff, newsize);
  340. }
  341. G(L)->GCthreshold = 2*G(L)->nblocks; /* new threshold */
  342. }
  343. static void do1gcTM (lua_State *L, Udata *udata) {
  344. const TObject *tm = fasttm(L, udata->uv.metatable, TM_GC);
  345. if (tm != NULL) {
  346. setobj2s(L->top, tm);
  347. setuvalue(L->top+1, udata);
  348. L->top += 2;
  349. luaD_call(L, L->top - 2, 0);
  350. }
  351. }
  352. static void callGCTM (lua_State *L) {
  353. lu_byte oldah = L->allowhook;
  354. L->allowhook = 0; /* stop debug hooks during GC tag methods */
  355. L->top++; /* reserve space to keep udata while runs its gc method */
  356. while (G(L)->tmudata != NULL) {
  357. GCObject *o = G(L)->tmudata;
  358. Udata *udata = gcotou(o);
  359. G(L)->tmudata = udata->uv.next; /* remove udata from `tmudata' */
  360. udata->uv.next = G(L)->rootudata; /* return it to `root' list */
  361. G(L)->rootudata = o;
  362. setuvalue(L->top - 1, udata); /* keep a reference to it */
  363. unmark(o);
  364. markfinalized(udata);
  365. do1gcTM(L, udata);
  366. }
  367. L->top--;
  368. L->allowhook = oldah; /* restore hooks */
  369. }
  370. void luaC_callallgcTM (lua_State *L) {
  371. separateudata(L);
  372. callGCTM(L); /* call their GC tag methods */
  373. }
  374. void luaC_sweep (lua_State *L, int all) {
  375. if (all) all = 256; /* larger than any mark */
  376. sweeplist(L, &G(L)->rootudata, all);
  377. sweepstrings(L, all);
  378. sweeplist(L, &G(L)->rootgc, all);
  379. }
  380. /* mark root set */
  381. static void markroot (GCState *st, lua_State *L) {
  382. global_State *G = st->G;
  383. markobject(st, defaultmeta(L));
  384. markobject(st, registry(L));
  385. traversestack(st, G->mainthread);
  386. if (L != G->mainthread) /* another thread is running? */
  387. markvalue(st, L); /* cannot collect it */
  388. }
  389. static void mark (lua_State *L) {
  390. GCState st;
  391. GCObject *wkv;
  392. st.G = G(L);
  393. st.tmark = NULL;
  394. st.wkv = st.wk = st.wv = NULL;
  395. markroot(&st, L);
  396. propagatemarks(&st); /* mark all reachable objects */
  397. cleartablevalues(st.wkv);
  398. cleartablevalues(st.wv);
  399. wkv = st.wkv; /* keys must be cleared after preserving udata */
  400. st.wkv = NULL;
  401. st.wv = NULL;
  402. separateudata(L); /* separate userdata to be preserved */
  403. marktmu(&st); /* mark `preserved' userdata */
  404. propagatemarks(&st); /* remark, to propagate `preserveness' */
  405. cleartablekeys(wkv);
  406. /* `propagatemarks' may resuscitate some weak tables; clear them too */
  407. cleartablekeys(st.wk);
  408. cleartablevalues(st.wv);
  409. cleartablekeys(st.wkv);
  410. cleartablevalues(st.wkv);
  411. }
  412. void luaC_collectgarbage (lua_State *L) {
  413. mark(L);
  414. luaC_sweep(L, 0);
  415. checkSizes(L);
  416. callGCTM(L);
  417. }
  418. void luaC_link (lua_State *L, GCObject *o, lu_byte tt) {
  419. o->gch.next = G(L)->rootgc;
  420. G(L)->rootgc = o;
  421. o->gch.marked = 0;
  422. o->gch.tt = tt;
  423. }