lgc.c 13 KB

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