lgc.c 13 KB

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