lgc.c 13 KB

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