lgc.c 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  1. /*
  2. ** $Id: lgc.c,v 2.215 2016/12/22 13:08:50 roberto Exp $
  3. ** Garbage Collector
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lgc_c
  7. #define LUA_CORE
  8. #include "lprefix.h"
  9. #include <string.h>
  10. #include "lua.h"
  11. #include "ldebug.h"
  12. #include "ldo.h"
  13. #include "lfunc.h"
  14. #include "lgc.h"
  15. #include "lmem.h"
  16. #include "lobject.h"
  17. #include "lstate.h"
  18. #include "lstring.h"
  19. #include "ltable.h"
  20. #include "ltm.h"
  21. /*
  22. ** internal state for collector while inside the atomic phase. The
  23. ** collector should never be in this state while running regular code.
  24. */
  25. #define GCSinsideatomic (GCSpause + 1)
  26. /*
  27. ** cost of sweeping one element (the size of a small object divided
  28. ** by some adjust for the sweep speed)
  29. */
  30. #define GCSWEEPCOST ((sizeof(TString) + 4) / 4)
  31. /* maximum number of elements to sweep in each single step */
  32. #define GCSWEEPMAX (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4))
  33. /* cost of calling one finalizer */
  34. #define GCFINALIZECOST GCSWEEPCOST
  35. /*
  36. ** macro to adjust 'stepmul': 'stepmul' is actually used like
  37. ** 'stepmul / STEPMULADJ' (value chosen by tests)
  38. */
  39. #define STEPMULADJ 200
  40. /*
  41. ** macro to adjust 'pause': 'pause' is actually used like
  42. ** 'pause / PAUSEADJ' (value chosen by tests)
  43. */
  44. #define PAUSEADJ 100
  45. /*
  46. ** 'makewhite' erases all color bits then sets only the current white
  47. ** bit
  48. */
  49. #define maskcolors (~(bitmask(BLACKBIT) | WHITEBITS))
  50. #define makewhite(g,x) \
  51. (x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g)))
  52. #define white2gray(x) resetbits(x->marked, WHITEBITS)
  53. #define black2gray(x) resetbit(x->marked, BLACKBIT)
  54. #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
  55. #define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))
  56. #define checkconsistency(obj) \
  57. lua_longassert(!iscollectable(obj) || righttt(obj))
  58. #define markvalue(g,o) { checkconsistency(o); \
  59. if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
  60. #define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); }
  61. /*
  62. ** mark an object that can be NULL (either because it is really optional,
  63. ** or it was stripped as debug info, or inside an uncompleted structure)
  64. */
  65. #define markobjectN(g,t) { if (t) markobject(g,t); }
  66. static void reallymarkobject (global_State *g, GCObject *o);
  67. /*
  68. ** {======================================================
  69. ** Generic functions
  70. ** =======================================================
  71. */
  72. /*
  73. ** one after last element in a hash array
  74. */
  75. #define gnodelast(h) gnode(h, cast(size_t, sizenode(h)))
  76. /*
  77. ** link collectable object 'o' into list pointed by 'p'
  78. */
  79. #define linkgclist(o,p) ((o)->gclist = (p), (p) = obj2gco(o))
  80. /*
  81. ** If key is not marked, mark its entry as dead. This allows key to be
  82. ** collected, but keeps its entry in the table. A dead node is needed
  83. ** when Lua looks up for a key (it may be part of a chain) and when
  84. ** traversing a weak table (key might be removed from the table during
  85. ** traversal). Other places never manipulate dead keys, because its
  86. ** associated nil value is enough to signal that the entry is logically
  87. ** empty.
  88. */
  89. static void removeentry (Node *n) {
  90. lua_assert(ttisnil(gval(n)));
  91. if (valiswhite(gkey(n)))
  92. setdeadvalue(wgkey(n)); /* unused and unmarked key; remove it */
  93. }
  94. /*
  95. ** tells whether a key or value can be cleared from a weak
  96. ** table. Non-collectable objects are never removed from weak
  97. ** tables. Strings behave as 'values', so are never removed too. for
  98. ** other objects: if really collected, cannot keep them; for objects
  99. ** being finalized, keep them in keys, but not in values
  100. */
  101. static int iscleared (global_State *g, const TValue *o) {
  102. if (!iscollectable(o)) return 0;
  103. else if (ttisstring(o)) {
  104. markobject(g, tsvalue(o)); /* strings are 'values', so are never weak */
  105. return 0;
  106. }
  107. else return iswhite(gcvalue(o));
  108. }
  109. /*
  110. ** barrier that moves collector forward, that is, mark the white object
  111. ** being pointed by a black object. (If in sweep phase, clear the black
  112. ** object to white [sweep it] to avoid other barrier calls for this
  113. ** same object.)
  114. */
  115. void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
  116. global_State *g = G(L);
  117. lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
  118. if (keepinvariant(g)) /* must keep invariant? */
  119. reallymarkobject(g, v); /* restore invariant */
  120. else { /* sweep phase */
  121. lua_assert(issweepphase(g));
  122. makewhite(g, o); /* mark main obj. as white to avoid other barriers */
  123. }
  124. }
  125. /*
  126. ** barrier that moves collector backward, that is, mark the black object
  127. ** pointing to a white object as gray again.
  128. */
  129. void luaC_barrierback_ (lua_State *L, Table *t) {
  130. global_State *g = G(L);
  131. lua_assert(isblack(t) && !isdead(g, t));
  132. black2gray(t); /* make table gray (again) */
  133. linkgclist(t, g->grayagain);
  134. }
  135. /*
  136. ** barrier for assignments to closed upvalues. Because upvalues are
  137. ** shared among closures, it is impossible to know the color of all
  138. ** closures pointing to it. So, we assume that the object being assigned
  139. ** must be marked.
  140. */
  141. void luaC_upvalbarrier_ (lua_State *L, UpVal *uv) {
  142. global_State *g = G(L);
  143. GCObject *o = gcvalue(uv->v);
  144. lua_assert(!upisopen(uv)); /* ensured by macro luaC_upvalbarrier */
  145. if (keepinvariant(g))
  146. markobject(g, o);
  147. }
  148. void luaC_fix (lua_State *L, GCObject *o) {
  149. global_State *g = G(L);
  150. lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */
  151. white2gray(o); /* they will be gray forever */
  152. g->allgc = o->next; /* remove object from 'allgc' list */
  153. o->next = g->fixedgc; /* link it to 'fixedgc' list */
  154. g->fixedgc = o;
  155. }
  156. /*
  157. ** create a new collectable object (with given type and size) and link
  158. ** it to 'allgc' list.
  159. */
  160. GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
  161. global_State *g = G(L);
  162. GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz));
  163. o->marked = luaC_white(g);
  164. o->tt = tt;
  165. o->next = g->allgc;
  166. g->allgc = o;
  167. return o;
  168. }
  169. /* }====================================================== */
  170. /*
  171. ** {======================================================
  172. ** Mark functions
  173. ** =======================================================
  174. */
  175. /*
  176. ** mark an object. Userdata, strings, and closed upvalues are visited
  177. ** and turned black here. Other objects are marked gray and added
  178. ** to appropriate list to be visited (and turned black) later. (Open
  179. ** upvalues are already linked in 'headuv' list.)
  180. */
  181. static void reallymarkobject (global_State *g, GCObject *o) {
  182. reentry:
  183. white2gray(o);
  184. switch (o->tt) {
  185. case LUA_TSHRSTR: {
  186. gray2black(o);
  187. g->GCmemtrav += sizelstring(gco2ts(o)->shrlen);
  188. break;
  189. }
  190. case LUA_TLNGSTR: {
  191. gray2black(o);
  192. g->GCmemtrav += sizelstring(gco2ts(o)->u.lnglen);
  193. break;
  194. }
  195. case LUA_TUSERDATA: {
  196. TValue uvalue;
  197. markobjectN(g, gco2u(o)->metatable); /* mark its metatable */
  198. gray2black(o);
  199. g->GCmemtrav += sizeudata(gco2u(o));
  200. getuservalue(g->mainthread, gco2u(o), &uvalue);
  201. if (valiswhite(&uvalue)) { /* markvalue(g, &uvalue); */
  202. o = gcvalue(&uvalue);
  203. goto reentry;
  204. }
  205. break;
  206. }
  207. case LUA_TLCL: {
  208. linkgclist(gco2lcl(o), g->gray);
  209. break;
  210. }
  211. case LUA_TCCL: {
  212. linkgclist(gco2ccl(o), g->gray);
  213. break;
  214. }
  215. case LUA_TTABLE: {
  216. linkgclist(gco2t(o), g->gray);
  217. break;
  218. }
  219. case LUA_TTHREAD: {
  220. linkgclist(gco2th(o), g->gray);
  221. break;
  222. }
  223. case LUA_TPROTO: {
  224. linkgclist(gco2p(o), g->gray);
  225. break;
  226. }
  227. default: lua_assert(0); break;
  228. }
  229. }
  230. /*
  231. ** mark metamethods for basic types
  232. */
  233. static void markmt (global_State *g) {
  234. int i;
  235. for (i=0; i < LUA_NUMTAGS; i++)
  236. markobjectN(g, g->mt[i]);
  237. }
  238. /*
  239. ** mark all objects in list of being-finalized
  240. */
  241. static void markbeingfnz (global_State *g) {
  242. GCObject *o;
  243. for (o = g->tobefnz; o != NULL; o = o->next)
  244. markobject(g, o);
  245. }
  246. /*
  247. ** Mark all values stored in marked open upvalues from non-marked threads.
  248. ** (Values from marked threads were already marked when traversing the
  249. ** thread.) Remove from the list threads that no longer have upvalues and
  250. ** not-marked threads.
  251. */
  252. static void remarkupvals (global_State *g) {
  253. lua_State *thread;
  254. lua_State **p = &g->twups;
  255. while ((thread = *p) != NULL) {
  256. lua_assert(!isblack(thread)); /* threads are never black */
  257. if (isgray(thread) && thread->openupval != NULL)
  258. p = &thread->twups; /* keep marked thread with upvalues in the list */
  259. else { /* thread is not marked or without upvalues */
  260. UpVal *uv;
  261. *p = thread->twups; /* remove thread from the list */
  262. thread->twups = thread; /* mark that it is out of list */
  263. for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {
  264. if (uv->u.open.touched) {
  265. markvalue(g, uv->v); /* remark upvalue's value */
  266. uv->u.open.touched = 0;
  267. }
  268. }
  269. }
  270. }
  271. }
  272. /*
  273. ** mark root set and reset all gray lists, to start a new collection
  274. */
  275. static void restartcollection (global_State *g) {
  276. g->gray = g->grayagain = NULL;
  277. g->weak = g->allweak = g->ephemeron = NULL;
  278. markobject(g, g->mainthread);
  279. markvalue(g, &g->l_registry);
  280. markmt(g);
  281. markbeingfnz(g); /* mark any finalizing object left from previous cycle */
  282. }
  283. /* }====================================================== */
  284. /*
  285. ** {======================================================
  286. ** Traverse functions
  287. ** =======================================================
  288. */
  289. /*
  290. ** Traverse a table with weak values and link it to proper list. During
  291. ** propagate phase, keep it in 'grayagain' list, to be revisited in the
  292. ** atomic phase. In the atomic phase, if table has any white value,
  293. ** put it in 'weak' list, to be cleared.
  294. */
  295. static void traverseweakvalue (global_State *g, Table *h) {
  296. Node *n, *limit = gnodelast(h);
  297. /* if there is array part, assume it may have white values (it is not
  298. worth traversing it now just to check) */
  299. int hasclears = (h->sizearray > 0);
  300. for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
  301. checkdeadkey(n);
  302. if (ttisnil(gval(n))) /* entry is empty? */
  303. removeentry(n); /* remove it */
  304. else {
  305. lua_assert(!ttisnil(gkey(n)));
  306. markvalue(g, gkey(n)); /* mark key */
  307. if (!hasclears && iscleared(g, gval(n))) /* is there a white value? */
  308. hasclears = 1; /* table will have to be cleared */
  309. }
  310. }
  311. if (g->gcstate == GCSpropagate)
  312. linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
  313. else if (hasclears)
  314. linkgclist(h, g->weak); /* has to be cleared later */
  315. }
  316. /*
  317. ** Traverse an ephemeron table and link it to proper list. Returns true
  318. ** iff any object was marked during this traversal (which implies that
  319. ** convergence has to continue). During propagation phase, keep table
  320. ** in 'grayagain' list, to be visited again in the atomic phase. In
  321. ** the atomic phase, if table has any white->white entry, it has to
  322. ** be revisited during ephemeron convergence (as that key may turn
  323. ** black). Otherwise, if it has any white key, table has to be cleared
  324. ** (in the atomic phase).
  325. */
  326. static int traverseephemeron (global_State *g, Table *h) {
  327. int marked = 0; /* true if an object is marked in this traversal */
  328. int hasclears = 0; /* true if table has white keys */
  329. int hasww = 0; /* true if table has entry "white-key -> white-value" */
  330. Node *n, *limit = gnodelast(h);
  331. unsigned int i;
  332. /* traverse array part */
  333. for (i = 0; i < h->sizearray; i++) {
  334. if (valiswhite(&h->array[i])) {
  335. marked = 1;
  336. reallymarkobject(g, gcvalue(&h->array[i]));
  337. }
  338. }
  339. /* traverse hash part */
  340. for (n = gnode(h, 0); n < limit; n++) {
  341. checkdeadkey(n);
  342. if (ttisnil(gval(n))) /* entry is empty? */
  343. removeentry(n); /* remove it */
  344. else if (iscleared(g, gkey(n))) { /* key is not marked (yet)? */
  345. hasclears = 1; /* table must be cleared */
  346. if (valiswhite(gval(n))) /* value not marked yet? */
  347. hasww = 1; /* white-white entry */
  348. }
  349. else if (valiswhite(gval(n))) { /* value not marked yet? */
  350. marked = 1;
  351. reallymarkobject(g, gcvalue(gval(n))); /* mark it now */
  352. }
  353. }
  354. /* link table into proper list */
  355. if (g->gcstate == GCSpropagate)
  356. linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
  357. else if (hasww) /* table has white->white entries? */
  358. linkgclist(h, g->ephemeron); /* have to propagate again */
  359. else if (hasclears) /* table has white keys? */
  360. linkgclist(h, g->allweak); /* may have to clean white keys */
  361. return marked;
  362. }
  363. static void traversestrongtable (global_State *g, Table *h) {
  364. Node *n, *limit = gnodelast(h);
  365. unsigned int i;
  366. for (i = 0; i < h->sizearray; i++) /* traverse array part */
  367. markvalue(g, &h->array[i]);
  368. for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
  369. checkdeadkey(n);
  370. if (ttisnil(gval(n))) /* entry is empty? */
  371. removeentry(n); /* remove it */
  372. else {
  373. lua_assert(!ttisnil(gkey(n)));
  374. markvalue(g, gkey(n)); /* mark key */
  375. markvalue(g, gval(n)); /* mark value */
  376. }
  377. }
  378. }
  379. static lu_mem traversetable (global_State *g, Table *h) {
  380. const char *weakkey, *weakvalue;
  381. const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
  382. markobjectN(g, h->metatable);
  383. if (mode && ttisstring(mode) && /* is there a weak mode? */
  384. ((weakkey = strchr(svalue(mode), 'k')),
  385. (weakvalue = strchr(svalue(mode), 'v')),
  386. (weakkey || weakvalue))) { /* is really weak? */
  387. black2gray(h); /* keep table gray */
  388. if (!weakkey) /* strong keys? */
  389. traverseweakvalue(g, h);
  390. else if (!weakvalue) /* strong values? */
  391. traverseephemeron(g, h);
  392. else /* all weak */
  393. linkgclist(h, g->allweak); /* nothing to traverse now */
  394. }
  395. else /* not weak */
  396. traversestrongtable(g, h);
  397. return sizeof(Table) + sizeof(TValue) * h->sizearray +
  398. sizeof(Node) * cast(size_t, allocsizenode(h));
  399. }
  400. /*
  401. ** Traverse a prototype. (While a prototype is being build, its
  402. ** arrays can be larger than needed; the extra slots are filled with
  403. ** NULL, so the use of 'markobjectN')
  404. */
  405. static int traverseproto (global_State *g, Proto *f) {
  406. int i;
  407. if (f->cache && iswhite(f->cache))
  408. f->cache = NULL; /* allow cache to be collected */
  409. markobjectN(g, f->source);
  410. for (i = 0; i < f->sizek; i++) /* mark literals */
  411. markvalue(g, &f->k[i]);
  412. for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
  413. markobjectN(g, f->upvalues[i].name);
  414. for (i = 0; i < f->sizep; i++) /* mark nested protos */
  415. markobjectN(g, f->p[i]);
  416. for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
  417. markobjectN(g, f->locvars[i].varname);
  418. return sizeof(Proto) + sizeof(Instruction) * f->sizecode +
  419. sizeof(Proto *) * f->sizep +
  420. sizeof(TValue) * f->sizek +
  421. sizeof(int) * f->sizelineinfo +
  422. sizeof(LocVar) * f->sizelocvars +
  423. sizeof(Upvaldesc) * f->sizeupvalues;
  424. }
  425. static lu_mem traverseCclosure (global_State *g, CClosure *cl) {
  426. int i;
  427. for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */
  428. markvalue(g, &cl->upvalue[i]);
  429. return sizeCclosure(cl->nupvalues);
  430. }
  431. /*
  432. ** open upvalues point to values in a thread, so those values should
  433. ** be marked when the thread is traversed except in the atomic phase
  434. ** (because then the value cannot be changed by the thread and the
  435. ** thread may not be traversed again)
  436. */
  437. static lu_mem traverseLclosure (global_State *g, LClosure *cl) {
  438. int i;
  439. markobjectN(g, cl->p); /* mark its prototype */
  440. for (i = 0; i < cl->nupvalues; i++) { /* mark its upvalues */
  441. UpVal *uv = cl->upvals[i];
  442. if (uv != NULL) {
  443. if (upisopen(uv) && g->gcstate != GCSinsideatomic)
  444. uv->u.open.touched = 1; /* can be marked in 'remarkupvals' */
  445. else
  446. markvalue(g, uv->v);
  447. }
  448. }
  449. return sizeLclosure(cl->nupvalues);
  450. }
  451. static lu_mem traversethread (global_State *g, lua_State *th) {
  452. StkId o = th->stack;
  453. if (o == NULL)
  454. return 1; /* stack not completely built yet */
  455. lua_assert(g->gcstate == GCSinsideatomic ||
  456. th->openupval == NULL || isintwups(th));
  457. for (; o < th->top; o++) /* mark live elements in the stack */
  458. markvalue(g, o);
  459. if (g->gcstate == GCSinsideatomic) { /* final traversal? */
  460. StkId lim = th->stack + th->stacksize; /* real end of stack */
  461. for (; o < lim; o++) /* clear not-marked stack slice */
  462. setnilvalue(o);
  463. /* 'remarkupvals' may have removed thread from 'twups' list */
  464. if (!isintwups(th) && th->openupval != NULL) {
  465. th->twups = g->twups; /* link it back to the list */
  466. g->twups = th;
  467. }
  468. }
  469. else if (g->gckind != KGC_EMERGENCY)
  470. luaD_shrinkstack(th); /* do not change stack in emergency cycle */
  471. return (sizeof(lua_State) + sizeof(TValue) * th->stacksize +
  472. sizeof(CallInfo) * th->nci);
  473. }
  474. /*
  475. ** traverse one gray object, turning it to black (except for threads,
  476. ** which are always gray).
  477. */
  478. static void propagatemark (global_State *g) {
  479. lu_mem size;
  480. GCObject *o = g->gray;
  481. lua_assert(isgray(o));
  482. gray2black(o);
  483. switch (o->tt) {
  484. case LUA_TTABLE: {
  485. Table *h = gco2t(o);
  486. g->gray = h->gclist; /* remove from 'gray' list */
  487. size = traversetable(g, h);
  488. break;
  489. }
  490. case LUA_TLCL: {
  491. LClosure *cl = gco2lcl(o);
  492. g->gray = cl->gclist; /* remove from 'gray' list */
  493. size = traverseLclosure(g, cl);
  494. break;
  495. }
  496. case LUA_TCCL: {
  497. CClosure *cl = gco2ccl(o);
  498. g->gray = cl->gclist; /* remove from 'gray' list */
  499. size = traverseCclosure(g, cl);
  500. break;
  501. }
  502. case LUA_TTHREAD: {
  503. lua_State *th = gco2th(o);
  504. g->gray = th->gclist; /* remove from 'gray' list */
  505. linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
  506. black2gray(o);
  507. size = traversethread(g, th);
  508. break;
  509. }
  510. case LUA_TPROTO: {
  511. Proto *p = gco2p(o);
  512. g->gray = p->gclist; /* remove from 'gray' list */
  513. size = traverseproto(g, p);
  514. break;
  515. }
  516. default: lua_assert(0); return;
  517. }
  518. g->GCmemtrav += size;
  519. }
  520. static void propagateall (global_State *g) {
  521. while (g->gray) propagatemark(g);
  522. }
  523. static void convergeephemerons (global_State *g) {
  524. int changed;
  525. do {
  526. GCObject *w;
  527. GCObject *next = g->ephemeron; /* get ephemeron list */
  528. g->ephemeron = NULL; /* tables may return to this list when traversed */
  529. changed = 0;
  530. while ((w = next) != NULL) {
  531. next = gco2t(w)->gclist;
  532. if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */
  533. propagateall(g); /* propagate changes */
  534. changed = 1; /* will have to revisit all ephemeron tables */
  535. }
  536. }
  537. } while (changed);
  538. }
  539. /* }====================================================== */
  540. /*
  541. ** {======================================================
  542. ** Sweep Functions
  543. ** =======================================================
  544. */
  545. /*
  546. ** clear entries with unmarked keys from all weaktables in list 'l' up
  547. ** to element 'f'
  548. */
  549. static void clearkeys (global_State *g, GCObject *l, GCObject *f) {
  550. for (; l != f; l = gco2t(l)->gclist) {
  551. Table *h = gco2t(l);
  552. Node *n, *limit = gnodelast(h);
  553. for (n = gnode(h, 0); n < limit; n++) {
  554. if (!ttisnil(gval(n)) && (iscleared(g, gkey(n)))) {
  555. setnilvalue(gval(n)); /* remove value ... */
  556. removeentry(n); /* and remove entry from table */
  557. }
  558. }
  559. }
  560. }
  561. /*
  562. ** clear entries with unmarked values from all weaktables in list 'l' up
  563. ** to element 'f'
  564. */
  565. static void clearvalues (global_State *g, GCObject *l, GCObject *f) {
  566. for (; l != f; l = gco2t(l)->gclist) {
  567. Table *h = gco2t(l);
  568. Node *n, *limit = gnodelast(h);
  569. unsigned int i;
  570. for (i = 0; i < h->sizearray; i++) {
  571. TValue *o = &h->array[i];
  572. if (iscleared(g, o)) /* value was collected? */
  573. setnilvalue(o); /* remove value */
  574. }
  575. for (n = gnode(h, 0); n < limit; n++) {
  576. if (!ttisnil(gval(n)) && iscleared(g, gval(n))) {
  577. setnilvalue(gval(n)); /* remove value ... */
  578. removeentry(n); /* and remove entry from table */
  579. }
  580. }
  581. }
  582. }
  583. void luaC_upvdeccount (lua_State *L, UpVal *uv) {
  584. lua_assert(uv->refcount > 0);
  585. uv->refcount--;
  586. if (uv->refcount == 0 && !upisopen(uv))
  587. luaM_free(L, uv);
  588. }
  589. static void freeLclosure (lua_State *L, LClosure *cl) {
  590. int i;
  591. for (i = 0; i < cl->nupvalues; i++) {
  592. UpVal *uv = cl->upvals[i];
  593. if (uv)
  594. luaC_upvdeccount(L, uv);
  595. }
  596. luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
  597. }
  598. static void freeobj (lua_State *L, GCObject *o) {
  599. switch (o->tt) {
  600. case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
  601. case LUA_TLCL: {
  602. freeLclosure(L, gco2lcl(o));
  603. break;
  604. }
  605. case LUA_TCCL: {
  606. luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));
  607. break;
  608. }
  609. case LUA_TTABLE: luaH_free(L, gco2t(o)); break;
  610. case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
  611. case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
  612. case LUA_TSHRSTR:
  613. luaS_remove(L, gco2ts(o)); /* remove it from hash table */
  614. luaM_freemem(L, o, sizelstring(gco2ts(o)->shrlen));
  615. break;
  616. case LUA_TLNGSTR: {
  617. luaM_freemem(L, o, sizelstring(gco2ts(o)->u.lnglen));
  618. break;
  619. }
  620. default: lua_assert(0);
  621. }
  622. }
  623. #define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM)
  624. static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);
  625. /*
  626. ** sweep at most 'count' elements from a list of GCObjects erasing dead
  627. ** objects, where a dead object is one marked with the old (non current)
  628. ** white; change all non-dead objects back to white, preparing for next
  629. ** collection cycle. Return where to continue the traversal or NULL if
  630. ** list is finished.
  631. */
  632. static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
  633. global_State *g = G(L);
  634. int ow = otherwhite(g);
  635. int white = luaC_white(g); /* current white */
  636. while (*p != NULL && count-- > 0) {
  637. GCObject *curr = *p;
  638. int marked = curr->marked;
  639. if (isdeadm(ow, marked)) { /* is 'curr' dead? */
  640. *p = curr->next; /* remove 'curr' from list */
  641. freeobj(L, curr); /* erase 'curr' */
  642. }
  643. else { /* change mark to 'white' */
  644. curr->marked = cast_byte((marked & maskcolors) | white);
  645. p = &curr->next; /* go to next element */
  646. }
  647. }
  648. return (*p == NULL) ? NULL : p;
  649. }
  650. /*
  651. ** sweep a list until a live object (or end of list)
  652. */
  653. static GCObject **sweeptolive (lua_State *L, GCObject **p) {
  654. GCObject **old = p;
  655. do {
  656. p = sweeplist(L, p, 1);
  657. } while (p == old);
  658. return p;
  659. }
  660. /* }====================================================== */
  661. /*
  662. ** {======================================================
  663. ** Finalization
  664. ** =======================================================
  665. */
  666. /*
  667. ** If possible, shrink string table
  668. */
  669. static void checkSizes (lua_State *L, global_State *g) {
  670. if (g->gckind != KGC_EMERGENCY) {
  671. l_mem olddebt = g->GCdebt;
  672. if (g->strt.nuse < g->strt.size / 4) /* string table too big? */
  673. luaS_resize(L, g->strt.size / 2); /* shrink it a little */
  674. g->GCestimate += g->GCdebt - olddebt; /* update estimate */
  675. }
  676. }
  677. static GCObject *udata2finalize (global_State *g) {
  678. GCObject *o = g->tobefnz; /* get first element */
  679. lua_assert(tofinalize(o));
  680. g->tobefnz = o->next; /* remove it from 'tobefnz' list */
  681. o->next = g->allgc; /* return it to 'allgc' list */
  682. g->allgc = o;
  683. resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */
  684. if (issweepphase(g))
  685. makewhite(g, o); /* "sweep" object */
  686. return o;
  687. }
  688. static void dothecall (lua_State *L, void *ud) {
  689. UNUSED(ud);
  690. luaD_callnoyield(L, L->top - 2, 0);
  691. }
  692. static void GCTM (lua_State *L, int propagateerrors) {
  693. global_State *g = G(L);
  694. const TValue *tm;
  695. TValue v;
  696. setgcovalue(L, &v, udata2finalize(g));
  697. tm = luaT_gettmbyobj(L, &v, TM_GC);
  698. if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */
  699. int status;
  700. lu_byte oldah = L->allowhook;
  701. int running = g->gcrunning;
  702. L->allowhook = 0; /* stop debug hooks during GC metamethod */
  703. g->gcrunning = 0; /* avoid GC steps */
  704. setobj2s(L, L->top, tm); /* push finalizer... */
  705. setobj2s(L, L->top + 1, &v); /* ... and its argument */
  706. L->top += 2; /* and (next line) call the finalizer */
  707. L->ci->callstatus |= CIST_FIN; /* will run a finalizer */
  708. status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
  709. L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */
  710. L->allowhook = oldah; /* restore hooks */
  711. g->gcrunning = running; /* restore state */
  712. if (status != LUA_OK && propagateerrors) { /* error while running __gc? */
  713. if (status == LUA_ERRRUN) { /* is there an error object? */
  714. const char *msg = (ttisstring(L->top - 1))
  715. ? svalue(L->top - 1)
  716. : "no message";
  717. luaO_pushfstring(L, "error in __gc metamethod (%s)", msg);
  718. status = LUA_ERRGCMM; /* error in __gc metamethod */
  719. }
  720. luaD_throw(L, status); /* re-throw error */
  721. }
  722. }
  723. }
  724. /*
  725. ** call a few (up to 'g->gcfinnum') finalizers
  726. */
  727. static int runafewfinalizers (lua_State *L) {
  728. global_State *g = G(L);
  729. unsigned int i;
  730. lua_assert(!g->tobefnz || g->gcfinnum > 0);
  731. for (i = 0; g->tobefnz && i < g->gcfinnum; i++)
  732. GCTM(L, 1); /* call one finalizer */
  733. g->gcfinnum = (!g->tobefnz) ? 0 /* nothing more to finalize? */
  734. : g->gcfinnum * 2; /* else call a few more next time */
  735. return i;
  736. }
  737. /*
  738. ** call all pending finalizers
  739. */
  740. static void callallpendingfinalizers (lua_State *L) {
  741. global_State *g = G(L);
  742. while (g->tobefnz)
  743. GCTM(L, 0);
  744. }
  745. /*
  746. ** find last 'next' field in list 'p' list (to add elements in its end)
  747. */
  748. static GCObject **findlast (GCObject **p) {
  749. while (*p != NULL)
  750. p = &(*p)->next;
  751. return p;
  752. }
  753. /*
  754. ** move all unreachable objects (or 'all' objects) that need
  755. ** finalization from list 'finobj' to list 'tobefnz' (to be finalized)
  756. */
  757. static void separatetobefnz (global_State *g, int all) {
  758. GCObject *curr;
  759. GCObject **p = &g->finobj;
  760. GCObject **lastnext = findlast(&g->tobefnz);
  761. while ((curr = *p) != NULL) { /* traverse all finalizable objects */
  762. lua_assert(tofinalize(curr));
  763. if (!(iswhite(curr) || all)) /* not being collected? */
  764. p = &curr->next; /* don't bother with it */
  765. else {
  766. *p = curr->next; /* remove 'curr' from 'finobj' list */
  767. curr->next = *lastnext; /* link at the end of 'tobefnz' list */
  768. *lastnext = curr;
  769. lastnext = &curr->next;
  770. }
  771. }
  772. }
  773. /*
  774. ** if object 'o' has a finalizer, remove it from 'allgc' list (must
  775. ** search the list to find it) and link it in 'finobj' list.
  776. */
  777. void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
  778. global_State *g = G(L);
  779. if (tofinalize(o) || /* obj. is already marked... */
  780. gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */
  781. return; /* nothing to be done */
  782. else { /* move 'o' to 'finobj' list */
  783. GCObject **p;
  784. if (issweepphase(g)) {
  785. makewhite(g, o); /* "sweep" object 'o' */
  786. if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */
  787. g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */
  788. }
  789. /* search for pointer pointing to 'o' */
  790. for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
  791. *p = o->next; /* remove 'o' from 'allgc' list */
  792. o->next = g->finobj; /* link it in 'finobj' list */
  793. g->finobj = o;
  794. l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */
  795. }
  796. }
  797. /* }====================================================== */
  798. /*
  799. ** {======================================================
  800. ** GC control
  801. ** =======================================================
  802. */
  803. /*
  804. ** Set a reasonable "time" to wait before starting a new GC cycle; cycle
  805. ** will start when memory use hits threshold. (Division by 'estimate'
  806. ** should be OK: it cannot be zero (because Lua cannot even start with
  807. ** less than PAUSEADJ bytes).
  808. */
  809. static void setpause (global_State *g) {
  810. l_mem threshold, debt;
  811. l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */
  812. lua_assert(estimate > 0);
  813. threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */
  814. ? estimate * g->gcpause /* no overflow */
  815. : MAX_LMEM; /* overflow; truncate to maximum */
  816. debt = gettotalbytes(g) - threshold;
  817. luaE_setdebt(g, debt);
  818. }
  819. /*
  820. ** Enter first sweep phase.
  821. ** The call to 'sweeplist' tries to make pointer point to an object
  822. ** inside the list (instead of to the header), so that the real sweep do
  823. ** not need to skip objects created between "now" and the start of the
  824. ** real sweep.
  825. */
  826. static void entersweep (lua_State *L) {
  827. global_State *g = G(L);
  828. g->gcstate = GCSswpallgc;
  829. lua_assert(g->sweepgc == NULL);
  830. g->sweepgc = sweeplist(L, &g->allgc, 1);
  831. }
  832. void luaC_freeallobjects (lua_State *L) {
  833. global_State *g = G(L);
  834. separatetobefnz(g, 1); /* separate all objects with finalizers */
  835. lua_assert(g->finobj == NULL);
  836. callallpendingfinalizers(L);
  837. lua_assert(g->tobefnz == NULL);
  838. g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */
  839. g->gckind = KGC_NORMAL;
  840. sweepwholelist(L, &g->finobj);
  841. sweepwholelist(L, &g->allgc);
  842. sweepwholelist(L, &g->fixedgc); /* collect fixed objects */
  843. lua_assert(g->strt.nuse == 0);
  844. }
  845. static l_mem atomic (lua_State *L) {
  846. global_State *g = G(L);
  847. l_mem work;
  848. GCObject *origweak, *origall;
  849. GCObject *grayagain = g->grayagain; /* save original list */
  850. lua_assert(g->ephemeron == NULL && g->weak == NULL);
  851. lua_assert(!iswhite(g->mainthread));
  852. g->gcstate = GCSinsideatomic;
  853. g->GCmemtrav = 0; /* start counting work */
  854. markobject(g, L); /* mark running thread */
  855. /* registry and global metatables may be changed by API */
  856. markvalue(g, &g->l_registry);
  857. markmt(g); /* mark global metatables */
  858. /* remark occasional upvalues of (maybe) dead threads */
  859. remarkupvals(g);
  860. propagateall(g); /* propagate changes */
  861. work = g->GCmemtrav; /* stop counting (do not recount 'grayagain') */
  862. g->gray = grayagain;
  863. propagateall(g); /* traverse 'grayagain' list */
  864. g->GCmemtrav = 0; /* restart counting */
  865. convergeephemerons(g);
  866. /* at this point, all strongly accessible objects are marked. */
  867. /* Clear values from weak tables, before checking finalizers */
  868. clearvalues(g, g->weak, NULL);
  869. clearvalues(g, g->allweak, NULL);
  870. origweak = g->weak; origall = g->allweak;
  871. work += g->GCmemtrav; /* stop counting (objects being finalized) */
  872. separatetobefnz(g, 0); /* separate objects to be finalized */
  873. g->gcfinnum = 1; /* there may be objects to be finalized */
  874. markbeingfnz(g); /* mark objects that will be finalized */
  875. propagateall(g); /* remark, to propagate 'resurrection' */
  876. g->GCmemtrav = 0; /* restart counting */
  877. convergeephemerons(g);
  878. /* at this point, all resurrected objects are marked. */
  879. /* remove dead objects from weak tables */
  880. clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */
  881. clearkeys(g, g->allweak, NULL); /* clear keys from all 'allweak' tables */
  882. /* clear values from resurrected weak tables */
  883. clearvalues(g, g->weak, origweak);
  884. clearvalues(g, g->allweak, origall);
  885. luaS_clearcache(g);
  886. g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
  887. work += g->GCmemtrav; /* complete counting */
  888. return work; /* estimate of memory marked by 'atomic' */
  889. }
  890. static lu_mem sweepstep (lua_State *L, global_State *g,
  891. int nextstate, GCObject **nextlist) {
  892. if (g->sweepgc) {
  893. l_mem olddebt = g->GCdebt;
  894. g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
  895. g->GCestimate += g->GCdebt - olddebt; /* update estimate */
  896. if (g->sweepgc) /* is there still something to sweep? */
  897. return (GCSWEEPMAX * GCSWEEPCOST);
  898. }
  899. /* else enter next state */
  900. g->gcstate = nextstate;
  901. g->sweepgc = nextlist;
  902. return 0;
  903. }
  904. static lu_mem singlestep (lua_State *L) {
  905. global_State *g = G(L);
  906. switch (g->gcstate) {
  907. case GCSpause: {
  908. g->GCmemtrav = g->strt.size * sizeof(GCObject*);
  909. restartcollection(g);
  910. g->gcstate = GCSpropagate;
  911. return g->GCmemtrav;
  912. }
  913. case GCSpropagate: {
  914. g->GCmemtrav = 0;
  915. lua_assert(g->gray);
  916. propagatemark(g);
  917. if (g->gray == NULL) /* no more gray objects? */
  918. g->gcstate = GCSatomic; /* finish propagate phase */
  919. return g->GCmemtrav; /* memory traversed in this step */
  920. }
  921. case GCSatomic: {
  922. lu_mem work;
  923. propagateall(g); /* make sure gray list is empty */
  924. work = atomic(L); /* work is what was traversed by 'atomic' */
  925. entersweep(L);
  926. g->GCestimate = gettotalbytes(g); /* first estimate */;
  927. return work;
  928. }
  929. case GCSswpallgc: { /* sweep "regular" objects */
  930. return sweepstep(L, g, GCSswpfinobj, &g->finobj);
  931. }
  932. case GCSswpfinobj: { /* sweep objects with finalizers */
  933. return sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
  934. }
  935. case GCSswptobefnz: { /* sweep objects to be finalized */
  936. return sweepstep(L, g, GCSswpend, NULL);
  937. }
  938. case GCSswpend: { /* finish sweeps */
  939. makewhite(g, g->mainthread); /* sweep main thread */
  940. checkSizes(L, g);
  941. g->gcstate = GCScallfin;
  942. return 0;
  943. }
  944. case GCScallfin: { /* call remaining finalizers */
  945. if (g->tobefnz && g->gckind != KGC_EMERGENCY) {
  946. int n = runafewfinalizers(L);
  947. return (n * GCFINALIZECOST);
  948. }
  949. else { /* emergency mode or no more finalizers */
  950. g->gcstate = GCSpause; /* finish collection */
  951. return 0;
  952. }
  953. }
  954. default: lua_assert(0); return 0;
  955. }
  956. }
  957. /*
  958. ** advances the garbage collector until it reaches a state allowed
  959. ** by 'statemask'
  960. */
  961. void luaC_runtilstate (lua_State *L, int statesmask) {
  962. global_State *g = G(L);
  963. while (!testbit(statesmask, g->gcstate))
  964. singlestep(L);
  965. }
  966. /*
  967. ** get GC debt and convert it from Kb to 'work units' (avoid zero debt
  968. ** and overflows)
  969. */
  970. static l_mem getdebt (global_State *g) {
  971. l_mem debt = g->GCdebt;
  972. int stepmul = g->gcstepmul;
  973. if (debt <= 0) return 0; /* minimal debt */
  974. else {
  975. debt = (debt / STEPMULADJ) + 1;
  976. debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM;
  977. return debt;
  978. }
  979. }
  980. /*
  981. ** performs a basic GC step when collector is running
  982. */
  983. void luaC_step (lua_State *L) {
  984. global_State *g = G(L);
  985. l_mem debt = getdebt(g); /* GC deficit (be paid now) */
  986. if (!g->gcrunning) { /* not running? */
  987. luaE_setdebt(g, -GCSTEPSIZE * 10); /* avoid being called too often */
  988. return;
  989. }
  990. do { /* repeat until pause or enough "credit" (negative debt) */
  991. lu_mem work = singlestep(L); /* perform one single step */
  992. debt -= work;
  993. } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);
  994. if (g->gcstate == GCSpause)
  995. setpause(g); /* pause until next cycle */
  996. else {
  997. debt = (debt / g->gcstepmul) * STEPMULADJ; /* convert 'work units' to Kb */
  998. luaE_setdebt(g, debt);
  999. runafewfinalizers(L);
  1000. }
  1001. }
  1002. /*
  1003. ** Performs a full GC cycle; if 'isemergency', set a flag to avoid
  1004. ** some operations which could change the interpreter state in some
  1005. ** unexpected ways (running finalizers and shrinking some structures).
  1006. ** Before running the collection, check 'keepinvariant'; if it is true,
  1007. ** there may be some objects marked as black, so the collector has
  1008. ** to sweep all objects to turn them back to white (as white has not
  1009. ** changed, nothing will be collected).
  1010. */
  1011. void luaC_fullgc (lua_State *L, int isemergency) {
  1012. global_State *g = G(L);
  1013. lua_assert(g->gckind == KGC_NORMAL);
  1014. if (isemergency) g->gckind = KGC_EMERGENCY; /* set flag */
  1015. if (keepinvariant(g)) { /* black objects? */
  1016. entersweep(L); /* sweep everything to turn them back to white */
  1017. }
  1018. /* finish any pending sweep phase to start a new cycle */
  1019. luaC_runtilstate(L, bitmask(GCSpause));
  1020. luaC_runtilstate(L, ~bitmask(GCSpause)); /* start new collection */
  1021. luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */
  1022. /* estimate must be correct after a full GC cycle */
  1023. lua_assert(g->GCestimate == gettotalbytes(g));
  1024. luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */
  1025. g->gckind = KGC_NORMAL;
  1026. setpause(g);
  1027. }
  1028. /* }====================================================== */