lgc.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. /*
  2. ** $Id: lgc.c,v 1.174 2003/07/07 13:32:19 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. if (lim < ci->top) lim = ci->top;
  198. }
  199. for (o = L1->stack; o < L1->top; o++)
  200. markobject(st, o);
  201. for (; o <= lim; o++)
  202. setnilvalue(o);
  203. checkstacksizes(L1, lim);
  204. }
  205. static void propagatemarks (GCState *st) {
  206. while (st->tmark) { /* traverse marked objects */
  207. switch (st->tmark->gch.tt) {
  208. case LUA_TTABLE: {
  209. Table *h = gcotoh(st->tmark);
  210. st->tmark = h->gclist;
  211. traversetable(st, h);
  212. break;
  213. }
  214. case LUA_TFUNCTION: {
  215. Closure *cl = gcotocl(st->tmark);
  216. st->tmark = cl->c.gclist;
  217. traverseclosure(st, cl);
  218. break;
  219. }
  220. case LUA_TTHREAD: {
  221. lua_State *th = gcototh(st->tmark);
  222. st->tmark = th->gclist;
  223. traversestack(st, th);
  224. break;
  225. }
  226. case LUA_TPROTO: {
  227. Proto *p = gcotop(st->tmark);
  228. st->tmark = p->gclist;
  229. traverseproto(st, p);
  230. break;
  231. }
  232. default: lua_assert(0);
  233. }
  234. }
  235. }
  236. /*
  237. ** The next function tells whether a key or value can be cleared from
  238. ** a weak table. Non-collectable objects are never removed from weak
  239. ** tables. Strings behave as `values', so are never removed too. for
  240. ** other objects: if really collected, cannot keep them; for userdata
  241. ** being finalized, keep them in keys, but not in values
  242. */
  243. static int iscleared (const TObject *o, int iskey) {
  244. if (!iscollectable(o)) return 0;
  245. if (ttisstring(o)) {
  246. stringmark(tsvalue(o)); /* strings are `values', so are never weak */
  247. return 0;
  248. }
  249. return !ismarked(gcvalue(o)) ||
  250. (ttisuserdata(o) && (!iskey && isfinalized(uvalue(o))));
  251. }
  252. static void removekey (Node *n) {
  253. setnilvalue(gval(n)); /* remove corresponding value ... */
  254. if (iscollectable(gkey(n)))
  255. setttype(gkey(n), LUA_TNONE); /* dead key; remove it */
  256. }
  257. /*
  258. ** clear collected entries from weaktables
  259. */
  260. static void cleartable (GCObject *l) {
  261. while (l) {
  262. Table *h = gcotoh(l);
  263. int i = h->sizearray;
  264. lua_assert(h->marked & (KEYWEAK | VALUEWEAK));
  265. if (h->marked & VALUEWEAK) {
  266. while (i--) {
  267. TObject *o = &h->array[i];
  268. if (iscleared(o, 0)) /* value was collected? */
  269. setnilvalue(o); /* remove value */
  270. }
  271. }
  272. i = sizenode(h);
  273. while (i--) {
  274. Node *n = gnode(h, i);
  275. if (!ttisnil(gval(n)) && /* non-empty entry? */
  276. (iscleared(gkey(n), 1) || iscleared(gval(n), 0)))
  277. removekey(n); /* remove entry from table */
  278. }
  279. l = h->gclist;
  280. }
  281. }
  282. static void freeobj (lua_State *L, GCObject *o) {
  283. switch (o->gch.tt) {
  284. case LUA_TPROTO: luaF_freeproto(L, gcotop(o)); break;
  285. case LUA_TFUNCTION: luaF_freeclosure(L, gcotocl(o)); break;
  286. case LUA_TUPVAL: luaM_freelem(L, gcotouv(o)); break;
  287. case LUA_TTABLE: luaH_free(L, gcotoh(o)); break;
  288. case LUA_TTHREAD: {
  289. lua_assert(gcototh(o) != L && gcototh(o) != G(L)->mainthread);
  290. luaE_freethread(L, gcototh(o));
  291. break;
  292. }
  293. case LUA_TSTRING: {
  294. luaM_free(L, o, sizestring(gcotots(o)->tsv.len));
  295. break;
  296. }
  297. case LUA_TUSERDATA: {
  298. luaM_free(L, o, sizeudata(gcotou(o)->uv.len));
  299. break;
  300. }
  301. default: lua_assert(0);
  302. }
  303. }
  304. static int sweeplist (lua_State *L, GCObject **p, int limit) {
  305. GCObject *curr;
  306. int count = 0; /* number of collected items */
  307. while ((curr = *p) != NULL) {
  308. if (curr->gch.marked > limit) {
  309. unmark(curr);
  310. p = &curr->gch.next;
  311. }
  312. else {
  313. count++;
  314. *p = curr->gch.next;
  315. freeobj(L, curr);
  316. }
  317. }
  318. return count;
  319. }
  320. static void sweepstrings (lua_State *L, int all) {
  321. int i;
  322. for (i=0; i<G(L)->strt.size; i++) { /* for each list */
  323. G(L)->strt.nuse -= sweeplist(L, &G(L)->strt.hash[i], all);
  324. }
  325. }
  326. static void checkSizes (lua_State *L) {
  327. /* check size of string hash */
  328. if (G(L)->strt.nuse < cast(lu_int32, G(L)->strt.size/4) &&
  329. G(L)->strt.size > MINSTRTABSIZE*2)
  330. luaS_resize(L, G(L)->strt.size/2); /* table is too big */
  331. /* check size of buffer */
  332. if (luaZ_sizebuffer(&G(L)->buff) > LUA_MINBUFFER*2) { /* buffer too big? */
  333. size_t newsize = luaZ_sizebuffer(&G(L)->buff) / 2;
  334. luaZ_resizebuffer(L, &G(L)->buff, newsize);
  335. }
  336. G(L)->GCthreshold = 2*G(L)->nblocks; /* new threshold */
  337. }
  338. static void do1gcTM (lua_State *L, Udata *udata) {
  339. const TObject *tm = fasttm(L, udata->uv.metatable, TM_GC);
  340. if (tm != NULL) {
  341. setobj2s(L->top, tm);
  342. setuvalue(L->top+1, udata);
  343. L->top += 2;
  344. luaD_call(L, L->top - 2, 0);
  345. }
  346. }
  347. void luaC_callGCTM (lua_State *L) {
  348. lu_byte oldah = L->allowhook;
  349. L->allowhook = 0; /* stop debug hooks during GC tag methods */
  350. L->top++; /* reserve space to keep udata while runs its gc method */
  351. while (G(L)->tmudata != NULL) {
  352. GCObject *o = G(L)->tmudata;
  353. Udata *udata = gcotou(o);
  354. G(L)->tmudata = udata->uv.next; /* remove udata from `tmudata' */
  355. udata->uv.next = G(L)->rootudata; /* return it to `root' list */
  356. G(L)->rootudata = o;
  357. setuvalue(L->top - 1, udata); /* keep a reference to it */
  358. unmark(o);
  359. do1gcTM(L, udata);
  360. }
  361. L->top--;
  362. L->allowhook = oldah; /* restore hooks */
  363. }
  364. void luaC_sweep (lua_State *L, int all) {
  365. if (all) all = 256; /* larger than any mark */
  366. sweeplist(L, &G(L)->rootudata, all);
  367. sweepstrings(L, all);
  368. sweeplist(L, &G(L)->rootgc, all);
  369. }
  370. /* mark root set */
  371. static void markroot (GCState *st, lua_State *L) {
  372. global_State *g = st->g;
  373. markobject(st, defaultmeta(L));
  374. markobject(st, registry(L));
  375. traversestack(st, g->mainthread);
  376. if (L != g->mainthread) /* another thread is running? */
  377. markvalue(st, L); /* cannot collect it */
  378. }
  379. static void mark (lua_State *L) {
  380. GCState st;
  381. st.g = G(L);
  382. st.tmark = NULL;
  383. st.w = NULL;
  384. markroot(&st, L);
  385. propagatemarks(&st); /* mark all reachable objects */
  386. luaC_separateudata(L); /* separate userdata to be preserved */
  387. marktmu(&st); /* mark `preserved' userdata */
  388. propagatemarks(&st); /* remark, to propagate `preserveness' */
  389. cleartable(st.w); /* remove collected objects from weak tables */
  390. }
  391. void luaC_collectgarbage (lua_State *L) {
  392. mark(L);
  393. luaC_sweep(L, 0);
  394. checkSizes(L);
  395. luaC_callGCTM(L);
  396. }
  397. void luaC_link (lua_State *L, GCObject *o, lu_byte tt) {
  398. o->gch.next = G(L)->rootgc;
  399. G(L)->rootgc = o;
  400. o->gch.marked = 0;
  401. o->gch.tt = tt;
  402. }