lgc.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724
  1. /*
  2. ** $Id: lgc.c $
  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 "llex.h"
  16. #include "lmem.h"
  17. #include "lobject.h"
  18. #include "lstate.h"
  19. #include "lstring.h"
  20. #include "ltable.h"
  21. #include "ltm.h"
  22. /*
  23. ** Number of fixed (luaC_fix) objects in a Lua state: metafield names,
  24. ** plus reserved words, plus "_ENV", plus the memory-error message.
  25. */
  26. #define NFIXED (TM_N + NUM_RESERVED + 2)
  27. /*
  28. ** Maximum number of elements to sweep in each single step.
  29. ** (Large enough to dissipate fixed overheads but small enough
  30. ** to allow small steps for the collector.)
  31. */
  32. #define GCSWEEPMAX 20
  33. /* mask with all color bits */
  34. #define maskcolors (bitmask(BLACKBIT) | WHITEBITS)
  35. /* mask with all GC bits */
  36. #define maskgcbits (maskcolors | AGEBITS)
  37. /* macro to erase all color bits then set only the current white bit */
  38. #define makewhite(g,x) \
  39. (x->marked = cast_byte((x->marked & ~maskcolors) | luaC_white(g)))
  40. /* make an object gray (neither white nor black) */
  41. #define set2gray(x) resetbits(x->marked, maskcolors)
  42. /* make an object black (coming from any color) */
  43. #define set2black(x) \
  44. (x->marked = cast_byte((x->marked & ~WHITEBITS) | bitmask(BLACKBIT)))
  45. #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
  46. #define keyiswhite(n) (keyiscollectable(n) && iswhite(gckey(n)))
  47. /*
  48. ** Protected access to objects in values
  49. */
  50. #define gcvalueN(o) (iscollectable(o) ? gcvalue(o) : NULL)
  51. /*
  52. ** Access to collectable objects in array part of tables
  53. */
  54. #define gcvalarr(t,i) \
  55. ((*getArrTag(t,i) & BIT_ISCOLLECTABLE) ? getArrVal(t,i)->gc : NULL)
  56. #define markvalue(g,o) { checkliveness(g->mainthread,o); \
  57. if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
  58. #define markkey(g, n) { if keyiswhite(n) reallymarkobject(g,gckey(n)); }
  59. #define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); }
  60. /*
  61. ** mark an object that can be NULL (either because it is really optional,
  62. ** or it was stripped as debug info, or inside an uncompleted structure)
  63. */
  64. #define markobjectN(g,t) { if (t) markobject(g,t); }
  65. static void reallymarkobject (global_State *g, GCObject *o);
  66. static l_obj atomic (lua_State *L);
  67. static void entersweep (lua_State *L);
  68. /*
  69. ** {======================================================
  70. ** Generic functions
  71. ** =======================================================
  72. */
  73. /*
  74. ** one after last element in a hash array
  75. */
  76. #define gnodelast(h) gnode(h, cast_sizet(sizenode(h)))
  77. static GCObject **getgclist (GCObject *o) {
  78. switch (o->tt) {
  79. case LUA_VTABLE: return &gco2t(o)->gclist;
  80. case LUA_VLCL: return &gco2lcl(o)->gclist;
  81. case LUA_VCCL: return &gco2ccl(o)->gclist;
  82. case LUA_VTHREAD: return &gco2th(o)->gclist;
  83. case LUA_VPROTO: return &gco2p(o)->gclist;
  84. case LUA_VUSERDATA: {
  85. Udata *u = gco2u(o);
  86. lua_assert(u->nuvalue > 0);
  87. return &u->gclist;
  88. }
  89. default: lua_assert(0); return 0;
  90. }
  91. }
  92. /*
  93. ** Link a collectable object 'o' with a known type into the list 'p'.
  94. ** (Must be a macro to access the 'gclist' field in different types.)
  95. */
  96. #define linkgclist(o,p) linkgclist_(obj2gco(o), &(o)->gclist, &(p))
  97. static void linkgclist_ (GCObject *o, GCObject **pnext, GCObject **list) {
  98. lua_assert(!isgray(o)); /* cannot be in a gray list */
  99. *pnext = *list;
  100. *list = o;
  101. set2gray(o); /* now it is */
  102. }
  103. /*
  104. ** Link a generic collectable object 'o' into the list 'p'.
  105. */
  106. #define linkobjgclist(o,p) linkgclist_(obj2gco(o), getgclist(o), &(p))
  107. /*
  108. ** Clear keys for empty entries in tables. If entry is empty, mark its
  109. ** entry as dead. This allows the collection of the key, but keeps its
  110. ** entry in the table: its removal could break a chain and could break
  111. ** a table traversal. Other places never manipulate dead keys, because
  112. ** its associated empty value is enough to signal that the entry is
  113. ** logically empty.
  114. */
  115. static void clearkey (Node *n) {
  116. lua_assert(isempty(gval(n)));
  117. if (keyiscollectable(n))
  118. setdeadkey(n); /* unused key; remove it */
  119. }
  120. /*
  121. ** tells whether a key or value can be cleared from a weak
  122. ** table. Non-collectable objects are never removed from weak
  123. ** tables. Strings behave as 'values', so are never removed too. for
  124. ** other objects: if really collected, cannot keep them; for objects
  125. ** being finalized, keep them in keys, but not in values
  126. */
  127. static int iscleared (global_State *g, const GCObject *o) {
  128. if (o == NULL) return 0; /* non-collectable value */
  129. else if (novariant(o->tt) == LUA_TSTRING) {
  130. markobject(g, o); /* strings are 'values', so are never weak */
  131. return 0;
  132. }
  133. else return iswhite(o);
  134. }
  135. /*
  136. ** Barrier that moves collector forward, that is, marks the white object
  137. ** 'v' being pointed by the black object 'o'. In the generational
  138. ** mode, 'v' must also become old, if 'o' is old; however, it cannot
  139. ** be changed directly to OLD, because it may still point to non-old
  140. ** objects. So, it is marked as OLD0. In the next cycle it will become
  141. ** OLD1, and in the next it will finally become OLD (regular old). By
  142. ** then, any object it points to will also be old. If called in the
  143. ** incremental sweep phase, it clears the black object to white (sweep
  144. ** it) to avoid other barrier calls for this same object. (That cannot
  145. ** be done is generational mode, as its sweep does not distinguish
  146. ** whites from deads.)
  147. */
  148. void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
  149. global_State *g = G(L);
  150. lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
  151. if (keepinvariant(g)) { /* must keep invariant? */
  152. reallymarkobject(g, v); /* restore invariant */
  153. if (isold(o)) {
  154. lua_assert(!isold(v)); /* white object could not be old */
  155. setage(v, G_OLD0); /* restore generational invariant */
  156. }
  157. }
  158. else { /* sweep phase */
  159. lua_assert(issweepphase(g));
  160. if (g->gckind != KGC_GENMINOR) /* incremental mode? */
  161. makewhite(g, o); /* mark 'o' as white to avoid other barriers */
  162. }
  163. }
  164. /*
  165. ** barrier that moves collector backward, that is, mark the black object
  166. ** pointing to a white object as gray again.
  167. */
  168. void luaC_barrierback_ (lua_State *L, GCObject *o) {
  169. global_State *g = G(L);
  170. lua_assert(isblack(o) && !isdead(g, o));
  171. lua_assert((g->gckind != KGC_GENMINOR)
  172. || (isold(o) && getage(o) != G_TOUCHED1));
  173. if (getage(o) == G_TOUCHED2) /* already in gray list? */
  174. set2gray(o); /* make it gray to become touched1 */
  175. else /* link it in 'grayagain' and paint it gray */
  176. linkobjgclist(o, g->grayagain);
  177. if (isold(o)) /* generational mode? */
  178. setage(o, G_TOUCHED1); /* touched in current cycle */
  179. }
  180. void luaC_fix (lua_State *L, GCObject *o) {
  181. global_State *g = G(L);
  182. lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */
  183. set2gray(o); /* they will be gray forever */
  184. setage(o, G_OLD); /* and old forever */
  185. g->allgc = o->next; /* remove object from 'allgc' list */
  186. o->next = g->fixedgc; /* link it to 'fixedgc' list */
  187. g->fixedgc = o;
  188. }
  189. /*
  190. ** create a new collectable object (with given type, size, and offset)
  191. ** and link it to 'allgc' list.
  192. */
  193. GCObject *luaC_newobjdt (lua_State *L, int tt, size_t sz, size_t offset) {
  194. global_State *g = G(L);
  195. char *p = cast_charp(luaM_newobject(L, novariant(tt), sz));
  196. GCObject *o = cast(GCObject *, p + offset);
  197. g->GCdebt--;
  198. o->marked = luaC_white(g);
  199. o->tt = tt;
  200. o->next = g->allgc;
  201. g->allgc = o;
  202. return o;
  203. }
  204. /*
  205. ** create a new collectable object with no offset.
  206. */
  207. GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
  208. return luaC_newobjdt(L, tt, sz, 0);
  209. }
  210. /* }====================================================== */
  211. /*
  212. ** {======================================================
  213. ** Mark functions
  214. ** =======================================================
  215. */
  216. /*
  217. ** Mark an object. Userdata with no user values, strings, and closed
  218. ** upvalues are visited and turned black here. Open upvalues are
  219. ** already indirectly linked through their respective threads in the
  220. ** 'twups' list, so they don't go to the gray list; nevertheless, they
  221. ** are kept gray to avoid barriers, as their values will be revisited
  222. ** by the thread or by 'remarkupvals'. Other objects are added to the
  223. ** gray list to be visited (and turned black) later. Both userdata and
  224. ** upvalues can call this function recursively, but this recursion goes
  225. ** for at most two levels: An upvalue cannot refer to another upvalue
  226. ** (only closures can), and a userdata's metatable must be a table.
  227. */
  228. static void reallymarkobject (global_State *g, GCObject *o) {
  229. g->marked++;
  230. switch (o->tt) {
  231. case LUA_VSHRSTR:
  232. case LUA_VLNGSTR: {
  233. set2black(o); /* nothing to visit */
  234. break;
  235. }
  236. case LUA_VUPVAL: {
  237. UpVal *uv = gco2upv(o);
  238. if (upisopen(uv))
  239. set2gray(uv); /* open upvalues are kept gray */
  240. else
  241. set2black(uv); /* closed upvalues are visited here */
  242. markvalue(g, uv->v.p); /* mark its content */
  243. break;
  244. }
  245. case LUA_VUSERDATA: {
  246. Udata *u = gco2u(o);
  247. if (u->nuvalue == 0) { /* no user values? */
  248. markobjectN(g, u->metatable); /* mark its metatable */
  249. set2black(u); /* nothing else to mark */
  250. break;
  251. }
  252. /* else... */
  253. } /* FALLTHROUGH */
  254. case LUA_VLCL: case LUA_VCCL: case LUA_VTABLE:
  255. case LUA_VTHREAD: case LUA_VPROTO: {
  256. linkobjgclist(o, g->gray); /* to be visited later */
  257. break;
  258. }
  259. default: lua_assert(0); break;
  260. }
  261. }
  262. /*
  263. ** mark metamethods for basic types
  264. */
  265. static void markmt (global_State *g) {
  266. int i;
  267. for (i=0; i < LUA_NUMTYPES; i++)
  268. markobjectN(g, g->mt[i]);
  269. }
  270. /*
  271. ** mark all objects in list of being-finalized
  272. */
  273. static l_obj markbeingfnz (global_State *g) {
  274. GCObject *o;
  275. l_obj count = 0;
  276. for (o = g->tobefnz; o != NULL; o = o->next) {
  277. count++;
  278. markobject(g, o);
  279. }
  280. return count;
  281. }
  282. /*
  283. ** For each non-marked thread, simulates a barrier between each open
  284. ** upvalue and its value. (If the thread is collected, the value will be
  285. ** assigned to the upvalue, but then it can be too late for the barrier
  286. ** to act. The "barrier" does not need to check colors: A non-marked
  287. ** thread must be young; upvalues cannot be older than their threads; so
  288. ** any visited upvalue must be young too.) Also removes the thread from
  289. ** the list, as it was already visited. Removes also threads with no
  290. ** upvalues, as they have nothing to be checked. (If the thread gets an
  291. ** upvalue later, it will be linked in the list again.)
  292. */
  293. static l_obj remarkupvals (global_State *g) {
  294. l_obj work = 0;
  295. lua_State *thread;
  296. lua_State **p = &g->twups;
  297. while ((thread = *p) != NULL) {
  298. if (!iswhite(thread) && thread->openupval != NULL)
  299. p = &thread->twups; /* keep marked thread with upvalues in the list */
  300. else { /* thread is not marked or without upvalues */
  301. UpVal *uv;
  302. lua_assert(!isold(thread) || thread->openupval == NULL);
  303. *p = thread->twups; /* remove thread from the list */
  304. thread->twups = thread; /* mark that it is out of list */
  305. for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {
  306. lua_assert(getage(uv) <= getage(thread));
  307. if (!iswhite(uv)) { /* upvalue already visited? */
  308. lua_assert(upisopen(uv) && isgray(uv));
  309. markvalue(g, uv->v.p); /* mark its value */
  310. }
  311. }
  312. }
  313. work++;
  314. }
  315. return work;
  316. }
  317. static void cleargraylists (global_State *g) {
  318. g->gray = g->grayagain = NULL;
  319. g->weak = g->allweak = g->ephemeron = NULL;
  320. }
  321. /*
  322. ** mark root set and reset all gray lists, to start a new collection.
  323. ** 'marked' is initialized with the number of fixed objects in the state,
  324. ** to count the total number of live objects during a cycle. (That is
  325. ** the metafield names, plus the reserved words, plus "_ENV" plus the
  326. ** memory-error message.)
  327. */
  328. static void restartcollection (global_State *g) {
  329. cleargraylists(g);
  330. g->marked = NFIXED;
  331. markobject(g, g->mainthread);
  332. markvalue(g, &g->l_registry);
  333. markmt(g);
  334. markbeingfnz(g); /* mark any finalizing object left from previous cycle */
  335. }
  336. /* }====================================================== */
  337. /*
  338. ** {======================================================
  339. ** Traverse functions
  340. ** =======================================================
  341. */
  342. /*
  343. ** Check whether object 'o' should be kept in the 'grayagain' list for
  344. ** post-processing by 'correctgraylist'. (It could put all old objects
  345. ** in the list and leave all the work to 'correctgraylist', but it is
  346. ** more efficient to avoid adding elements that will be removed.) Only
  347. ** TOUCHED1 objects need to be in the list. TOUCHED2 doesn't need to go
  348. ** back to a gray list, but then it must become OLD. (That is what
  349. ** 'correctgraylist' does when it finds a TOUCHED2 object.)
  350. */
  351. static void genlink (global_State *g, GCObject *o) {
  352. lua_assert(isblack(o));
  353. if (getage(o) == G_TOUCHED1) { /* touched in this cycle? */
  354. linkobjgclist(o, g->grayagain); /* link it back in 'grayagain' */
  355. } /* everything else do not need to be linked back */
  356. else if (getage(o) == G_TOUCHED2)
  357. setage(o, G_OLD); /* advance age */
  358. }
  359. /*
  360. ** Traverse a table with weak values and link it to proper list. During
  361. ** propagate phase, keep it in 'grayagain' list, to be revisited in the
  362. ** atomic phase. In the atomic phase, if table has any white value,
  363. ** put it in 'weak' list, to be cleared.
  364. */
  365. static void traverseweakvalue (global_State *g, Table *h) {
  366. Node *n, *limit = gnodelast(h);
  367. /* if there is array part, assume it may have white values (it is not
  368. worth traversing it now just to check) */
  369. int hasclears = (h->alimit > 0);
  370. for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
  371. if (isempty(gval(n))) /* entry is empty? */
  372. clearkey(n); /* clear its key */
  373. else {
  374. lua_assert(!keyisnil(n));
  375. markkey(g, n);
  376. if (!hasclears && iscleared(g, gcvalueN(gval(n)))) /* a white value? */
  377. hasclears = 1; /* table will have to be cleared */
  378. }
  379. }
  380. if (g->gcstate == GCSatomic && hasclears)
  381. linkgclist(h, g->weak); /* has to be cleared later */
  382. else
  383. linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
  384. }
  385. /*
  386. ** Traverse the array part of a table.
  387. */
  388. static int traversearray (global_State *g, Table *h) {
  389. unsigned asize = luaH_realasize(h);
  390. int marked = 0; /* true if some object is marked in this traversal */
  391. unsigned i;
  392. for (i = 0; i < asize; i++) {
  393. GCObject *o = gcvalarr(h, i);
  394. if (o != NULL && iswhite(o)) {
  395. marked = 1;
  396. reallymarkobject(g, o);
  397. }
  398. }
  399. return marked;
  400. }
  401. /*
  402. ** Traverse an ephemeron table and link it to proper list. Returns true
  403. ** iff any object was marked during this traversal (which implies that
  404. ** convergence has to continue). During propagation phase, keep table
  405. ** in 'grayagain' list, to be visited again in the atomic phase. In
  406. ** the atomic phase, if table has any white->white entry, it has to
  407. ** be revisited during ephemeron convergence (as that key may turn
  408. ** black). Otherwise, if it has any white key, table has to be cleared
  409. ** (in the atomic phase). In generational mode, some tables
  410. ** must be kept in some gray list for post-processing; this is done
  411. ** by 'genlink'.
  412. */
  413. static int traverseephemeron (global_State *g, Table *h, int inv) {
  414. int hasclears = 0; /* true if table has white keys */
  415. int hasww = 0; /* true if table has entry "white-key -> white-value" */
  416. unsigned int i;
  417. unsigned int nsize = sizenode(h);
  418. int marked = traversearray(g, h); /* traverse array part */
  419. /* traverse hash part; if 'inv', traverse descending
  420. (see 'convergeephemerons') */
  421. for (i = 0; i < nsize; i++) {
  422. Node *n = inv ? gnode(h, nsize - 1 - i) : gnode(h, i);
  423. if (isempty(gval(n))) /* entry is empty? */
  424. clearkey(n); /* clear its key */
  425. else if (iscleared(g, gckeyN(n))) { /* key is not marked (yet)? */
  426. hasclears = 1; /* table must be cleared */
  427. if (valiswhite(gval(n))) /* value not marked yet? */
  428. hasww = 1; /* white-white entry */
  429. }
  430. else if (valiswhite(gval(n))) { /* value not marked yet? */
  431. marked = 1;
  432. reallymarkobject(g, gcvalue(gval(n))); /* mark it now */
  433. }
  434. }
  435. /* link table into proper list */
  436. if (g->gcstate == GCSpropagate)
  437. linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
  438. else if (hasww) /* table has white->white entries? */
  439. linkgclist(h, g->ephemeron); /* have to propagate again */
  440. else if (hasclears) /* table has white keys? */
  441. linkgclist(h, g->allweak); /* may have to clean white keys */
  442. else
  443. genlink(g, obj2gco(h)); /* check whether collector still needs to see it */
  444. return marked;
  445. }
  446. static void traversestrongtable (global_State *g, Table *h) {
  447. Node *n, *limit = gnodelast(h);
  448. traversearray(g, h);
  449. for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
  450. if (isempty(gval(n))) /* entry is empty? */
  451. clearkey(n); /* clear its key */
  452. else {
  453. lua_assert(!keyisnil(n));
  454. markkey(g, n);
  455. markvalue(g, gval(n));
  456. }
  457. }
  458. genlink(g, obj2gco(h));
  459. }
  460. static void traversetable (global_State *g, Table *h) {
  461. const char *weakkey, *weakvalue;
  462. const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
  463. TString *smode;
  464. markobjectN(g, h->metatable);
  465. if (mode && ttisshrstring(mode) && /* is there a weak mode? */
  466. (cast_void(smode = tsvalue(mode)),
  467. cast_void(weakkey = strchr(getshrstr(smode), 'k')),
  468. cast_void(weakvalue = strchr(getshrstr(smode), 'v')),
  469. (weakkey || weakvalue))) { /* is really weak? */
  470. if (!weakkey) /* strong keys? */
  471. traverseweakvalue(g, h);
  472. else if (!weakvalue) /* strong values? */
  473. traverseephemeron(g, h, 0);
  474. else /* all weak */
  475. linkgclist(h, g->allweak); /* nothing to traverse now */
  476. }
  477. else /* not weak */
  478. traversestrongtable(g, h);
  479. }
  480. static void traverseudata (global_State *g, Udata *u) {
  481. int i;
  482. markobjectN(g, u->metatable); /* mark its metatable */
  483. for (i = 0; i < u->nuvalue; i++)
  484. markvalue(g, &u->uv[i].uv);
  485. genlink(g, obj2gco(u));
  486. }
  487. /*
  488. ** Traverse a prototype. (While a prototype is being build, its
  489. ** arrays can be larger than needed; the extra slots are filled with
  490. ** NULL, so the use of 'markobjectN')
  491. */
  492. static void traverseproto (global_State *g, Proto *f) {
  493. int i;
  494. markobjectN(g, f->source);
  495. for (i = 0; i < f->sizek; i++) /* mark literals */
  496. markvalue(g, &f->k[i]);
  497. for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
  498. markobjectN(g, f->upvalues[i].name);
  499. for (i = 0; i < f->sizep; i++) /* mark nested protos */
  500. markobjectN(g, f->p[i]);
  501. for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
  502. markobjectN(g, f->locvars[i].varname);
  503. }
  504. static void traverseCclosure (global_State *g, CClosure *cl) {
  505. int i;
  506. for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */
  507. markvalue(g, &cl->upvalue[i]);
  508. }
  509. /*
  510. ** Traverse a Lua closure, marking its prototype and its upvalues.
  511. ** (Both can be NULL while closure is being created.)
  512. */
  513. static void traverseLclosure (global_State *g, LClosure *cl) {
  514. int i;
  515. markobjectN(g, cl->p); /* mark its prototype */
  516. for (i = 0; i < cl->nupvalues; i++) { /* visit its upvalues */
  517. UpVal *uv = cl->upvals[i];
  518. markobjectN(g, uv); /* mark upvalue */
  519. }
  520. }
  521. /*
  522. ** Traverse a thread, marking the elements in the stack up to its top
  523. ** and cleaning the rest of the stack in the final traversal. That
  524. ** ensures that the entire stack have valid (non-dead) objects.
  525. ** Threads have no barriers. In gen. mode, old threads must be visited
  526. ** at every cycle, because they might point to young objects. In inc.
  527. ** mode, the thread can still be modified before the end of the cycle,
  528. ** and therefore it must be visited again in the atomic phase. To ensure
  529. ** these visits, threads must return to a gray list if they are not new
  530. ** (which can only happen in generational mode) or if the traverse is in
  531. ** the propagate phase (which can only happen in incremental mode).
  532. */
  533. static void traversethread (global_State *g, lua_State *th) {
  534. UpVal *uv;
  535. StkId o = th->stack.p;
  536. if (isold(th) || g->gcstate == GCSpropagate)
  537. linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
  538. if (o == NULL)
  539. return; /* stack not completely built yet */
  540. lua_assert(g->gcstate == GCSatomic ||
  541. th->openupval == NULL || isintwups(th));
  542. for (; o < th->top.p; o++) /* mark live elements in the stack */
  543. markvalue(g, s2v(o));
  544. for (uv = th->openupval; uv != NULL; uv = uv->u.open.next)
  545. markobject(g, uv); /* open upvalues cannot be collected */
  546. if (g->gcstate == GCSatomic) { /* final traversal? */
  547. if (!g->gcemergency)
  548. luaD_shrinkstack(th); /* do not change stack in emergency cycle */
  549. for (o = th->top.p; o < th->stack_last.p + EXTRA_STACK; o++)
  550. setnilvalue(s2v(o)); /* clear dead stack slice */
  551. /* 'remarkupvals' may have removed thread from 'twups' list */
  552. if (!isintwups(th) && th->openupval != NULL) {
  553. th->twups = g->twups; /* link it back to the list */
  554. g->twups = th;
  555. }
  556. }
  557. }
  558. /*
  559. ** traverse one gray object, turning it to black.
  560. */
  561. static void propagatemark (global_State *g) {
  562. GCObject *o = g->gray;
  563. nw2black(o);
  564. g->gray = *getgclist(o); /* remove from 'gray' list */
  565. switch (o->tt) {
  566. case LUA_VTABLE: traversetable(g, gco2t(o)); break;
  567. case LUA_VUSERDATA: traverseudata(g, gco2u(o)); break;
  568. case LUA_VLCL: traverseLclosure(g, gco2lcl(o)); break;
  569. case LUA_VCCL: traverseCclosure(g, gco2ccl(o)); break;
  570. case LUA_VPROTO: traverseproto(g, gco2p(o)); break;
  571. case LUA_VTHREAD: traversethread(g, gco2th(o)); break;
  572. default: lua_assert(0);
  573. }
  574. }
  575. static l_obj propagateall (global_State *g) {
  576. l_obj work = 0;
  577. while (g->gray) {
  578. propagatemark(g);
  579. work++;
  580. }
  581. return work;
  582. }
  583. /*
  584. ** Traverse all ephemeron tables propagating marks from keys to values.
  585. ** Repeat until it converges, that is, nothing new is marked. 'dir'
  586. ** inverts the direction of the traversals, trying to speed up
  587. ** convergence on chains in the same table.
  588. */
  589. static l_obj convergeephemerons (global_State *g) {
  590. int changed;
  591. l_obj work = 0;
  592. int dir = 0;
  593. do {
  594. GCObject *w;
  595. GCObject *next = g->ephemeron; /* get ephemeron list */
  596. g->ephemeron = NULL; /* tables may return to this list when traversed */
  597. changed = 0;
  598. while ((w = next) != NULL) { /* for each ephemeron table */
  599. Table *h = gco2t(w);
  600. next = h->gclist; /* list is rebuilt during loop */
  601. nw2black(h); /* out of the list (for now) */
  602. if (traverseephemeron(g, h, dir)) { /* marked some value? */
  603. propagateall(g); /* propagate changes */
  604. changed = 1; /* will have to revisit all ephemeron tables */
  605. }
  606. work++;
  607. }
  608. dir = !dir; /* invert direction next time */
  609. } while (changed); /* repeat until no more changes */
  610. return work;
  611. }
  612. /* }====================================================== */
  613. /*
  614. ** {======================================================
  615. ** Sweep Functions
  616. ** =======================================================
  617. */
  618. /*
  619. ** clear entries with unmarked keys from all weaktables in list 'l'
  620. */
  621. static l_obj clearbykeys (global_State *g, GCObject *l) {
  622. l_obj work = 0;
  623. for (; l; l = gco2t(l)->gclist) {
  624. Table *h = gco2t(l);
  625. Node *limit = gnodelast(h);
  626. Node *n;
  627. for (n = gnode(h, 0); n < limit; n++) {
  628. if (iscleared(g, gckeyN(n))) /* unmarked key? */
  629. setempty(gval(n)); /* remove entry */
  630. if (isempty(gval(n))) /* is entry empty? */
  631. clearkey(n); /* clear its key */
  632. }
  633. work++;
  634. }
  635. return work;
  636. }
  637. /*
  638. ** clear entries with unmarked values from all weaktables in list 'l' up
  639. ** to element 'f'
  640. */
  641. static l_obj clearbyvalues (global_State *g, GCObject *l, GCObject *f) {
  642. l_obj work = 0;
  643. for (; l != f; l = gco2t(l)->gclist) {
  644. Table *h = gco2t(l);
  645. Node *n, *limit = gnodelast(h);
  646. unsigned int i;
  647. unsigned int asize = luaH_realasize(h);
  648. for (i = 0; i < asize; i++) {
  649. GCObject *o = gcvalarr(h, i);
  650. if (iscleared(g, o)) /* value was collected? */
  651. *getArrTag(h, i) = LUA_VEMPTY; /* remove entry */
  652. }
  653. for (n = gnode(h, 0); n < limit; n++) {
  654. if (iscleared(g, gcvalueN(gval(n)))) /* unmarked value? */
  655. setempty(gval(n)); /* remove entry */
  656. if (isempty(gval(n))) /* is entry empty? */
  657. clearkey(n); /* clear its key */
  658. }
  659. work++;
  660. }
  661. return work;
  662. }
  663. static void freeupval (lua_State *L, UpVal *uv) {
  664. if (upisopen(uv))
  665. luaF_unlinkupval(uv);
  666. luaM_free(L, uv);
  667. }
  668. static void freeobj (lua_State *L, GCObject *o) {
  669. G(L)->totalobjs--;
  670. switch (o->tt) {
  671. case LUA_VPROTO:
  672. luaF_freeproto(L, gco2p(o));
  673. break;
  674. case LUA_VUPVAL:
  675. freeupval(L, gco2upv(o));
  676. break;
  677. case LUA_VLCL: {
  678. LClosure *cl = gco2lcl(o);
  679. luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
  680. break;
  681. }
  682. case LUA_VCCL: {
  683. CClosure *cl = gco2ccl(o);
  684. luaM_freemem(L, cl, sizeCclosure(cl->nupvalues));
  685. break;
  686. }
  687. case LUA_VTABLE:
  688. luaH_free(L, gco2t(o));
  689. break;
  690. case LUA_VTHREAD:
  691. luaE_freethread(L, gco2th(o));
  692. break;
  693. case LUA_VUSERDATA: {
  694. Udata *u = gco2u(o);
  695. luaM_freemem(L, o, sizeudata(u->nuvalue, u->len));
  696. break;
  697. }
  698. case LUA_VSHRSTR: {
  699. TString *ts = gco2ts(o);
  700. luaS_remove(L, ts); /* remove it from hash table */
  701. luaM_freemem(L, ts, sizestrshr(ts->shrlen));
  702. break;
  703. }
  704. case LUA_VLNGSTR: {
  705. TString *ts = gco2ts(o);
  706. if (ts->shrlen == LSTRMEM) /* must free external string? */
  707. (*ts->falloc)(ts->ud, ts->contents, ts->u.lnglen + 1, 0);
  708. luaM_freemem(L, ts, luaS_sizelngstr(ts->u.lnglen, ts->shrlen));
  709. break;
  710. }
  711. default: lua_assert(0);
  712. }
  713. }
  714. /*
  715. ** sweep at most 'countin' elements from a list of GCObjects erasing dead
  716. ** objects, where a dead object is one marked with the old (non current)
  717. ** white; change all non-dead objects back to white (and new), preparing
  718. ** for next collection cycle. Return where to continue the traversal or
  719. ** NULL if list is finished.
  720. */
  721. static GCObject **sweeplist (lua_State *L, GCObject **p, l_obj countin) {
  722. global_State *g = G(L);
  723. int ow = otherwhite(g);
  724. l_obj i;
  725. int white = luaC_white(g); /* current white */
  726. for (i = 0; *p != NULL && i < countin; i++) {
  727. GCObject *curr = *p;
  728. int marked = curr->marked;
  729. if (isdeadm(ow, marked)) { /* is 'curr' dead? */
  730. *p = curr->next; /* remove 'curr' from list */
  731. freeobj(L, curr); /* erase 'curr' */
  732. }
  733. else { /* change mark to 'white' and age to 'new' */
  734. curr->marked = cast_byte((marked & ~maskgcbits) | white | G_NEW);
  735. p = &curr->next; /* go to next element */
  736. }
  737. }
  738. return (*p == NULL) ? NULL : p;
  739. }
  740. /*
  741. ** sweep a list until a live object (or end of list)
  742. */
  743. static GCObject **sweeptolive (lua_State *L, GCObject **p) {
  744. GCObject **old = p;
  745. do {
  746. p = sweeplist(L, p, 1);
  747. } while (p == old);
  748. return p;
  749. }
  750. /* }====================================================== */
  751. /*
  752. ** {======================================================
  753. ** Finalization
  754. ** =======================================================
  755. */
  756. /*
  757. ** If possible, shrink string table.
  758. */
  759. static void checkSizes (lua_State *L, global_State *g) {
  760. if (!g->gcemergency) {
  761. if (g->strt.nuse < g->strt.size / 4) /* string table too big? */
  762. luaS_resize(L, g->strt.size / 2);
  763. }
  764. }
  765. /*
  766. ** Get the next udata to be finalized from the 'tobefnz' list, and
  767. ** link it back into the 'allgc' list.
  768. */
  769. static GCObject *udata2finalize (global_State *g) {
  770. GCObject *o = g->tobefnz; /* get first element */
  771. lua_assert(tofinalize(o));
  772. g->tobefnz = o->next; /* remove it from 'tobefnz' list */
  773. o->next = g->allgc; /* return it to 'allgc' list */
  774. g->allgc = o;
  775. resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */
  776. if (issweepphase(g))
  777. makewhite(g, o); /* "sweep" object */
  778. else if (getage(o) == G_OLD1)
  779. g->firstold1 = o; /* it is the first OLD1 object in the list */
  780. return o;
  781. }
  782. static void dothecall (lua_State *L, void *ud) {
  783. UNUSED(ud);
  784. luaD_callnoyield(L, L->top.p - 2, 0);
  785. }
  786. static void GCTM (lua_State *L) {
  787. global_State *g = G(L);
  788. const TValue *tm;
  789. TValue v;
  790. lua_assert(!g->gcemergency);
  791. setgcovalue(L, &v, udata2finalize(g));
  792. tm = luaT_gettmbyobj(L, &v, TM_GC);
  793. if (!notm(tm)) { /* is there a finalizer? */
  794. int status;
  795. lu_byte oldah = L->allowhook;
  796. int oldgcstp = g->gcstp;
  797. g->gcstp |= GCSTPGC; /* avoid GC steps */
  798. L->allowhook = 0; /* stop debug hooks during GC metamethod */
  799. setobj2s(L, L->top.p++, tm); /* push finalizer... */
  800. setobj2s(L, L->top.p++, &v); /* ... and its argument */
  801. L->ci->callstatus |= CIST_FIN; /* will run a finalizer */
  802. status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top.p - 2), 0);
  803. L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */
  804. L->allowhook = oldah; /* restore hooks */
  805. g->gcstp = oldgcstp; /* restore state */
  806. if (l_unlikely(status != LUA_OK)) { /* error while running __gc? */
  807. luaE_warnerror(L, "__gc");
  808. L->top.p--; /* pops error object */
  809. }
  810. }
  811. }
  812. /*
  813. ** call all pending finalizers
  814. */
  815. static void callallpendingfinalizers (lua_State *L) {
  816. global_State *g = G(L);
  817. while (g->tobefnz)
  818. GCTM(L);
  819. }
  820. /*
  821. ** find last 'next' field in list 'p' list (to add elements in its end)
  822. */
  823. static GCObject **findlast (GCObject **p) {
  824. while (*p != NULL)
  825. p = &(*p)->next;
  826. return p;
  827. }
  828. /*
  829. ** Move all unreachable objects (or 'all' objects) that need
  830. ** finalization from list 'finobj' to list 'tobefnz' (to be finalized).
  831. ** (Note that objects after 'finobjold1' cannot be white, so they
  832. ** don't need to be traversed. In incremental mode, 'finobjold1' is NULL,
  833. ** so the whole list is traversed.)
  834. */
  835. static void separatetobefnz (global_State *g, int all) {
  836. GCObject *curr;
  837. GCObject **p = &g->finobj;
  838. GCObject **lastnext = findlast(&g->tobefnz);
  839. while ((curr = *p) != g->finobjold1) { /* traverse all finalizable objects */
  840. lua_assert(tofinalize(curr));
  841. if (!(iswhite(curr) || all)) /* not being collected? */
  842. p = &curr->next; /* don't bother with it */
  843. else {
  844. if (curr == g->finobjsur) /* removing 'finobjsur'? */
  845. g->finobjsur = curr->next; /* correct it */
  846. *p = curr->next; /* remove 'curr' from 'finobj' list */
  847. curr->next = *lastnext; /* link at the end of 'tobefnz' list */
  848. *lastnext = curr;
  849. lastnext = &curr->next;
  850. }
  851. }
  852. }
  853. /*
  854. ** If pointer 'p' points to 'o', move it to the next element.
  855. */
  856. static void checkpointer (GCObject **p, GCObject *o) {
  857. if (o == *p)
  858. *p = o->next;
  859. }
  860. /*
  861. ** Correct pointers to objects inside 'allgc' list when
  862. ** object 'o' is being removed from the list.
  863. */
  864. static void correctpointers (global_State *g, GCObject *o) {
  865. checkpointer(&g->survival, o);
  866. checkpointer(&g->old1, o);
  867. checkpointer(&g->reallyold, o);
  868. checkpointer(&g->firstold1, o);
  869. }
  870. /*
  871. ** if object 'o' has a finalizer, remove it from 'allgc' list (must
  872. ** search the list to find it) and link it in 'finobj' list.
  873. */
  874. void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
  875. global_State *g = G(L);
  876. if (tofinalize(o) || /* obj. is already marked... */
  877. gfasttm(g, mt, TM_GC) == NULL || /* or has no finalizer... */
  878. (g->gcstp & GCSTPCLS)) /* or closing state? */
  879. return; /* nothing to be done */
  880. else { /* move 'o' to 'finobj' list */
  881. GCObject **p;
  882. if (issweepphase(g)) {
  883. makewhite(g, o); /* "sweep" object 'o' */
  884. if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */
  885. g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */
  886. }
  887. else
  888. correctpointers(g, o);
  889. /* search for pointer pointing to 'o' */
  890. for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
  891. *p = o->next; /* remove 'o' from 'allgc' list */
  892. o->next = g->finobj; /* link it in 'finobj' list */
  893. g->finobj = o;
  894. l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */
  895. }
  896. }
  897. /* }====================================================== */
  898. /*
  899. ** {======================================================
  900. ** Generational Collector
  901. ** =======================================================
  902. */
  903. /*
  904. ** Set the "time" to wait before starting a new incremental cycle;
  905. ** cycle will start when number of objects in use hits the threshold of
  906. ** approximately (marked * pause / 100).
  907. */
  908. static void setpause (global_State *g) {
  909. l_obj threshold = applygcparam(g, PAUSE, g->marked);
  910. l_obj debt = threshold - gettotalobjs(g);
  911. if (debt < 0) debt = 0;
  912. luaE_setdebt(g, debt);
  913. }
  914. /*
  915. ** Sweep a list of objects to enter generational mode. Deletes dead
  916. ** objects and turns the non dead to old. All non-dead threads---which
  917. ** are now old---must be in a gray list. Everything else is not in a
  918. ** gray list. Open upvalues are also kept gray.
  919. */
  920. static void sweep2old (lua_State *L, GCObject **p) {
  921. GCObject *curr;
  922. global_State *g = G(L);
  923. while ((curr = *p) != NULL) {
  924. if (iswhite(curr)) { /* is 'curr' dead? */
  925. lua_assert(isdead(g, curr));
  926. *p = curr->next; /* remove 'curr' from list */
  927. freeobj(L, curr); /* erase 'curr' */
  928. }
  929. else { /* all surviving objects become old */
  930. setage(curr, G_OLD);
  931. if (curr->tt == LUA_VTHREAD) { /* threads must be watched */
  932. lua_State *th = gco2th(curr);
  933. linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
  934. }
  935. else if (curr->tt == LUA_VUPVAL && upisopen(gco2upv(curr)))
  936. set2gray(curr); /* open upvalues are always gray */
  937. else /* everything else is black */
  938. nw2black(curr);
  939. p = &curr->next; /* go to next element */
  940. }
  941. }
  942. }
  943. /*
  944. ** Sweep for generational mode. Delete dead objects. (Because the
  945. ** collection is not incremental, there are no "new white" objects
  946. ** during the sweep. So, any white object must be dead.) For
  947. ** non-dead objects, advance their ages and clear the color of
  948. ** new objects. (Old objects keep their colors.)
  949. ** The ages of G_TOUCHED1 and G_TOUCHED2 objects cannot be advanced
  950. ** here, because these old-generation objects are usually not swept
  951. ** here. They will all be advanced in 'correctgraylist'. That function
  952. ** will also remove objects turned white here from any gray list.
  953. */
  954. static GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p,
  955. GCObject *limit, GCObject **pfirstold1,
  956. l_obj *paddedold) {
  957. static const lu_byte nextage[] = {
  958. G_SURVIVAL, /* from G_NEW */
  959. G_OLD1, /* from G_SURVIVAL */
  960. G_OLD1, /* from G_OLD0 */
  961. G_OLD, /* from G_OLD1 */
  962. G_OLD, /* from G_OLD (do not change) */
  963. G_TOUCHED1, /* from G_TOUCHED1 (do not change) */
  964. G_TOUCHED2 /* from G_TOUCHED2 (do not change) */
  965. };
  966. l_obj addedold = 0;
  967. int white = luaC_white(g);
  968. GCObject *curr;
  969. while ((curr = *p) != limit) {
  970. if (iswhite(curr)) { /* is 'curr' dead? */
  971. lua_assert(!isold(curr) && isdead(g, curr));
  972. *p = curr->next; /* remove 'curr' from list */
  973. freeobj(L, curr); /* erase 'curr' */
  974. }
  975. else { /* correct mark and age */
  976. int age = getage(curr);
  977. if (age == G_NEW) { /* new objects go back to white */
  978. int marked = curr->marked & ~maskgcbits; /* erase GC bits */
  979. curr->marked = cast_byte(marked | G_SURVIVAL | white);
  980. }
  981. else { /* all other objects will be old, and so keep their color */
  982. lua_assert(age != G_OLD1); /* advanced in 'markold' */
  983. setage(curr, nextage[age]);
  984. if (getage(curr) == G_OLD1) {
  985. addedold++; /* one more object becoming old */
  986. if (*pfirstold1 == NULL)
  987. *pfirstold1 = curr; /* first OLD1 object in the list */
  988. }
  989. }
  990. p = &curr->next; /* go to next element */
  991. }
  992. }
  993. *paddedold += addedold;
  994. return p;
  995. }
  996. /*
  997. ** Correct a list of gray objects. Return a pointer to the last element
  998. ** left on the list, so that we can link another list to the end of
  999. ** this one.
  1000. ** Because this correction is done after sweeping, young objects might
  1001. ** be turned white and still be in the list. They are only removed.
  1002. ** 'TOUCHED1' objects are advanced to 'TOUCHED2' and remain on the list;
  1003. ** Non-white threads also remain on the list. 'TOUCHED2' objects and
  1004. ** anything else become regular old, are marked black, and are removed
  1005. ** from the list.
  1006. */
  1007. static GCObject **correctgraylist (GCObject **p) {
  1008. GCObject *curr;
  1009. while ((curr = *p) != NULL) {
  1010. GCObject **next = getgclist(curr);
  1011. if (iswhite(curr))
  1012. goto remove; /* remove all white objects */
  1013. else if (getage(curr) == G_TOUCHED1) { /* touched in this cycle? */
  1014. lua_assert(isgray(curr));
  1015. nw2black(curr); /* make it black, for next barrier */
  1016. setage(curr, G_TOUCHED2);
  1017. goto remain; /* keep it in the list and go to next element */
  1018. }
  1019. else if (curr->tt == LUA_VTHREAD) {
  1020. lua_assert(isgray(curr));
  1021. goto remain; /* keep non-white threads on the list */
  1022. }
  1023. else { /* everything else is removed */
  1024. lua_assert(isold(curr)); /* young objects should be white here */
  1025. if (getage(curr) == G_TOUCHED2) /* advance from TOUCHED2... */
  1026. setage(curr, G_OLD); /* ... to OLD */
  1027. nw2black(curr); /* make object black (to be removed) */
  1028. goto remove;
  1029. }
  1030. remove: *p = *next; continue;
  1031. remain: p = next; continue;
  1032. }
  1033. return p;
  1034. }
  1035. /*
  1036. ** Correct all gray lists, coalescing them into 'grayagain'.
  1037. */
  1038. static void correctgraylists (global_State *g) {
  1039. GCObject **list = correctgraylist(&g->grayagain);
  1040. *list = g->weak; g->weak = NULL;
  1041. list = correctgraylist(list);
  1042. *list = g->allweak; g->allweak = NULL;
  1043. list = correctgraylist(list);
  1044. *list = g->ephemeron; g->ephemeron = NULL;
  1045. correctgraylist(list);
  1046. }
  1047. /*
  1048. ** Mark black 'OLD1' objects when starting a new young collection.
  1049. ** Gray objects are already in some gray list, and so will be visited in
  1050. ** the atomic step.
  1051. */
  1052. static void markold (global_State *g, GCObject *from, GCObject *to) {
  1053. GCObject *p;
  1054. for (p = from; p != to; p = p->next) {
  1055. if (getage(p) == G_OLD1) {
  1056. lua_assert(!iswhite(p));
  1057. setage(p, G_OLD); /* now they are old */
  1058. if (isblack(p))
  1059. reallymarkobject(g, p);
  1060. }
  1061. }
  1062. }
  1063. /*
  1064. ** Finish a young-generation collection.
  1065. */
  1066. static void finishgencycle (lua_State *L, global_State *g) {
  1067. correctgraylists(g);
  1068. checkSizes(L, g);
  1069. g->gcstate = GCSpropagate; /* skip restart */
  1070. if (!g->gcemergency)
  1071. callallpendingfinalizers(L);
  1072. }
  1073. /*
  1074. ** Shifts from a minor collection to major collections. It starts in
  1075. ** the "sweep all" state to clear all objects, which are mostly black
  1076. ** in generational mode.
  1077. */
  1078. static void minor2inc (lua_State *L, global_State *g, int kind) {
  1079. g->GCmajorminor = g->marked; /* number of live objects */
  1080. g->gckind = kind;
  1081. g->reallyold = g->old1 = g->survival = NULL;
  1082. g->finobjrold = g->finobjold1 = g->finobjsur = NULL;
  1083. entersweep(L); /* continue as an incremental cycle */
  1084. /* set a debt equal to the step size */
  1085. luaE_setdebt(g, applygcparam(g, STEPSIZE, 100));
  1086. }
  1087. /*
  1088. ** Decide whether to shift to major mode. It tests two conditions:
  1089. ** 1) Whether the number of added old objects in this collection is more
  1090. ** than half the number of new objects. ('step' is the number of objects
  1091. ** created between minor collections. Except for forward barriers, it
  1092. ** is the maximum number of objects that can become old in each minor
  1093. ** collection.)
  1094. ** 2) Whether the accumulated number of added old objects is larger
  1095. ** than 'minormajor'% of the number of lived objects after the last
  1096. ** major collection. (That percentage is computed in 'limit'.)
  1097. */
  1098. static int checkminormajor (global_State *g, l_obj addedold1) {
  1099. l_obj step = applygcparam(g, MINORMUL, g->GCmajorminor);
  1100. l_obj limit = applygcparam(g, MINORMAJOR, g->GCmajorminor);
  1101. return (addedold1 >= (step >> 1) || g->marked >= limit);
  1102. }
  1103. /*
  1104. ** Does a young collection. First, mark 'OLD1' objects. Then does the
  1105. ** atomic step. Then, check whether to continue in minor mode. If so,
  1106. ** sweep all lists and advance pointers. Finally, finish the collection.
  1107. */
  1108. static void youngcollection (lua_State *L, global_State *g) {
  1109. l_obj addedold1 = 0;
  1110. l_obj marked = g->marked; /* preserve 'g->marked' */
  1111. GCObject **psurvival; /* to point to first non-dead survival object */
  1112. GCObject *dummy; /* dummy out parameter to 'sweepgen' */
  1113. lua_assert(g->gcstate == GCSpropagate);
  1114. if (g->firstold1) { /* are there regular OLD1 objects? */
  1115. markold(g, g->firstold1, g->reallyold); /* mark them */
  1116. g->firstold1 = NULL; /* no more OLD1 objects (for now) */
  1117. }
  1118. markold(g, g->finobj, g->finobjrold);
  1119. markold(g, g->tobefnz, NULL);
  1120. atomic(L); /* will lose 'g->marked' */
  1121. /* sweep nursery and get a pointer to its last live element */
  1122. g->gcstate = GCSswpallgc;
  1123. psurvival = sweepgen(L, g, &g->allgc, g->survival, &g->firstold1, &addedold1);
  1124. /* sweep 'survival' */
  1125. sweepgen(L, g, psurvival, g->old1, &g->firstold1, &addedold1);
  1126. g->reallyold = g->old1;
  1127. g->old1 = *psurvival; /* 'survival' survivals are old now */
  1128. g->survival = g->allgc; /* all news are survivals */
  1129. /* repeat for 'finobj' lists */
  1130. dummy = NULL; /* no 'firstold1' optimization for 'finobj' lists */
  1131. psurvival = sweepgen(L, g, &g->finobj, g->finobjsur, &dummy, &addedold1);
  1132. /* sweep 'survival' */
  1133. sweepgen(L, g, psurvival, g->finobjold1, &dummy, &addedold1);
  1134. g->finobjrold = g->finobjold1;
  1135. g->finobjold1 = *psurvival; /* 'survival' survivals are old now */
  1136. g->finobjsur = g->finobj; /* all news are survivals */
  1137. sweepgen(L, g, &g->tobefnz, NULL, &dummy, &addedold1);
  1138. /* keep total number of added old1 objects */
  1139. g->marked = marked + addedold1;
  1140. /* decide whether to shift to major mode */
  1141. if (checkminormajor(g, addedold1)) {
  1142. minor2inc(L, g, KGC_GENMAJOR); /* go to major mode */
  1143. g->marked = 0; /* avoid pause in first major cycle */
  1144. }
  1145. else
  1146. finishgencycle(L, g); /* still in minor mode; finish it */
  1147. }
  1148. /*
  1149. ** Clears all gray lists, sweeps objects, and prepare sublists to enter
  1150. ** generational mode. The sweeps remove dead objects and turn all
  1151. ** surviving objects to old. Threads go back to 'grayagain'; everything
  1152. ** else is turned black (not in any gray list).
  1153. */
  1154. static void atomic2gen (lua_State *L, global_State *g) {
  1155. cleargraylists(g);
  1156. /* sweep all elements making them old */
  1157. g->gcstate = GCSswpallgc;
  1158. sweep2old(L, &g->allgc);
  1159. /* everything alive now is old */
  1160. g->reallyold = g->old1 = g->survival = g->allgc;
  1161. g->firstold1 = NULL; /* there are no OLD1 objects anywhere */
  1162. /* repeat for 'finobj' lists */
  1163. sweep2old(L, &g->finobj);
  1164. g->finobjrold = g->finobjold1 = g->finobjsur = g->finobj;
  1165. sweep2old(L, &g->tobefnz);
  1166. g->gckind = KGC_GENMINOR;
  1167. g->GCmajorminor = g->marked; /* "base" for number of objects */
  1168. g->marked = 0; /* to count the number of added old1 objects */
  1169. finishgencycle(L, g);
  1170. }
  1171. /*
  1172. ** Set debt for the next minor collection, which will happen when
  1173. ** total number of objects grows 'genminormul'%.
  1174. */
  1175. static void setminordebt (global_State *g) {
  1176. luaE_setdebt(g, applygcparam(g, MINORMUL, g->GCmajorminor));
  1177. }
  1178. /*
  1179. ** Enter generational mode. Must go until the end of an atomic cycle
  1180. ** to ensure that all objects are correctly marked and weak tables
  1181. ** are cleared. Then, turn all objects into old and finishes the
  1182. ** collection.
  1183. */
  1184. static void entergen (lua_State *L, global_State *g) {
  1185. luaC_runtilstate(L, GCSpause, 1); /* prepare to start a new cycle */
  1186. luaC_runtilstate(L, GCSpropagate, 1); /* start new cycle */
  1187. atomic(L); /* propagates all and then do the atomic stuff */
  1188. atomic2gen(L, g);
  1189. setminordebt(g); /* set debt assuming next cycle will be minor */
  1190. }
  1191. /*
  1192. ** Change collector mode to 'newmode'.
  1193. */
  1194. void luaC_changemode (lua_State *L, int newmode) {
  1195. global_State *g = G(L);
  1196. if (g->gckind == KGC_GENMAJOR) /* doing major collections? */
  1197. g->gckind = KGC_INC; /* already incremental but in name */
  1198. if (newmode != g->gckind) { /* does it need to change? */
  1199. if (newmode == KGC_INC) /* entering incremental mode? */
  1200. minor2inc(L, g, KGC_INC); /* entering incremental mode */
  1201. else {
  1202. lua_assert(newmode == KGC_GENMINOR);
  1203. entergen(L, g);
  1204. }
  1205. }
  1206. }
  1207. /*
  1208. ** Does a full collection in generational mode.
  1209. */
  1210. static void fullgen (lua_State *L, global_State *g) {
  1211. minor2inc(L, g, KGC_INC);
  1212. entergen(L, g);
  1213. }
  1214. /*
  1215. ** After an atomic incremental step from a major collection,
  1216. ** check whether collector could return to minor collections.
  1217. ** It checks whether the number of objects 'tobecollected'
  1218. ** is greater than 'majorminor'% of the number of objects added
  1219. ** since the last collection ('addedobjs').
  1220. */
  1221. static int checkmajorminor (lua_State *L, global_State *g) {
  1222. if (g->gckind == KGC_GENMAJOR) { /* generational mode? */
  1223. l_obj numobjs = gettotalobjs(g);
  1224. l_obj addedobjs = numobjs - g->GCmajorminor;
  1225. l_obj limit = applygcparam(g, MAJORMINOR, addedobjs);
  1226. l_obj tobecollected = numobjs - g->marked;
  1227. if (tobecollected > limit) {
  1228. atomic2gen(L, g); /* return to generational mode */
  1229. setminordebt(g);
  1230. return 0; /* exit incremental collection */
  1231. }
  1232. }
  1233. g->GCmajorminor = g->marked; /* prepare for next collection */
  1234. return 1; /* stay doing incremental collections */
  1235. }
  1236. /* }====================================================== */
  1237. /*
  1238. ** {======================================================
  1239. ** GC control
  1240. ** =======================================================
  1241. */
  1242. /*
  1243. ** Enter first sweep phase.
  1244. ** The call to 'sweeptolive' makes the pointer point to an object
  1245. ** inside the list (instead of to the header), so that the real sweep do
  1246. ** not need to skip objects created between "now" and the start of the
  1247. ** real sweep.
  1248. */
  1249. static void entersweep (lua_State *L) {
  1250. global_State *g = G(L);
  1251. g->gcstate = GCSswpallgc;
  1252. lua_assert(g->sweepgc == NULL);
  1253. g->sweepgc = sweeptolive(L, &g->allgc);
  1254. }
  1255. /*
  1256. ** Delete all objects in list 'p' until (but not including) object
  1257. ** 'limit'.
  1258. */
  1259. static void deletelist (lua_State *L, GCObject *p, GCObject *limit) {
  1260. while (p != limit) {
  1261. GCObject *next = p->next;
  1262. freeobj(L, p);
  1263. p = next;
  1264. }
  1265. }
  1266. /*
  1267. ** Call all finalizers of the objects in the given Lua state, and
  1268. ** then free all objects, except for the main thread.
  1269. */
  1270. void luaC_freeallobjects (lua_State *L) {
  1271. global_State *g = G(L);
  1272. g->gcstp = GCSTPCLS; /* no extra finalizers after here */
  1273. luaC_changemode(L, KGC_INC);
  1274. separatetobefnz(g, 1); /* separate all objects with finalizers */
  1275. lua_assert(g->finobj == NULL);
  1276. callallpendingfinalizers(L);
  1277. deletelist(L, g->allgc, obj2gco(g->mainthread));
  1278. lua_assert(g->finobj == NULL); /* no new finalizers */
  1279. deletelist(L, g->fixedgc, NULL); /* collect fixed objects */
  1280. lua_assert(g->strt.nuse == 0);
  1281. }
  1282. static l_obj atomic (lua_State *L) {
  1283. l_obj work = 0;
  1284. global_State *g = G(L);
  1285. GCObject *origweak, *origall;
  1286. GCObject *grayagain = g->grayagain; /* save original list */
  1287. g->grayagain = NULL;
  1288. lua_assert(g->ephemeron == NULL && g->weak == NULL);
  1289. lua_assert(!iswhite(g->mainthread));
  1290. g->gcstate = GCSatomic;
  1291. markobject(g, L); /* mark running thread */
  1292. /* registry and global metatables may be changed by API */
  1293. markvalue(g, &g->l_registry);
  1294. markmt(g); /* mark global metatables */
  1295. work += propagateall(g); /* empties 'gray' list */
  1296. /* remark occasional upvalues of (maybe) dead threads */
  1297. work += remarkupvals(g);
  1298. work += propagateall(g); /* propagate changes */
  1299. g->gray = grayagain;
  1300. work += propagateall(g); /* traverse 'grayagain' list */
  1301. work += convergeephemerons(g);
  1302. /* at this point, all strongly accessible objects are marked. */
  1303. /* Clear values from weak tables, before checking finalizers */
  1304. work += clearbyvalues(g, g->weak, NULL);
  1305. work += clearbyvalues(g, g->allweak, NULL);
  1306. origweak = g->weak; origall = g->allweak;
  1307. separatetobefnz(g, 0); /* separate objects to be finalized */
  1308. work += markbeingfnz(g); /* mark objects that will be finalized */
  1309. work += propagateall(g); /* remark, to propagate 'resurrection' */
  1310. work += convergeephemerons(g);
  1311. /* at this point, all resurrected objects are marked. */
  1312. /* remove dead objects from weak tables */
  1313. work += clearbykeys(g, g->ephemeron); /* clear keys from all ephemeron */
  1314. work += clearbykeys(g, g->allweak); /* clear keys from all 'allweak' */
  1315. /* clear values from resurrected weak tables */
  1316. work += clearbyvalues(g, g->weak, origweak);
  1317. work += clearbyvalues(g, g->allweak, origall);
  1318. luaS_clearcache(g);
  1319. g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
  1320. lua_assert(g->gray == NULL);
  1321. return work;
  1322. }
  1323. /*
  1324. ** Do a sweep step. The normal case (not fast) sweeps at most GCSWEEPMAX
  1325. ** elements. The fast case sweeps the whole list.
  1326. */
  1327. static void sweepstep (lua_State *L, global_State *g,
  1328. int nextstate, GCObject **nextlist, int fast) {
  1329. if (g->sweepgc)
  1330. g->sweepgc = sweeplist(L, g->sweepgc, fast ? MAX_LOBJ : GCSWEEPMAX);
  1331. else { /* enter next state */
  1332. g->gcstate = nextstate;
  1333. g->sweepgc = nextlist;
  1334. }
  1335. }
  1336. /*
  1337. ** Performs one incremental "step" in an incremental garbage collection.
  1338. ** For indivisible work, a step goes to the next state. When marking
  1339. ** (propagating), a step traverses one object. When sweeping, a step
  1340. ** sweeps GCSWEEPMAX objects, to avoid a big overhead for sweeping
  1341. ** objects one by one. (Sweeping is inexpensive, no matter the
  1342. ** object.) When 'fast' is true, 'singlestep' tries to finish a state
  1343. ** "as fast as possible". In particular, it skips the propagation
  1344. ** phase and leaves all objects to be traversed by the atomic phase:
  1345. ** That avoids traversing twice some objects, such as threads and
  1346. ** weak tables.
  1347. */
  1348. static l_obj singlestep (lua_State *L, int fast) {
  1349. global_State *g = G(L);
  1350. l_obj work;
  1351. lua_assert(!g->gcstopem); /* collector is not reentrant */
  1352. g->gcstopem = 1; /* no emergency collections while collecting */
  1353. switch (g->gcstate) {
  1354. case GCSpause: {
  1355. restartcollection(g);
  1356. g->gcstate = GCSpropagate;
  1357. work = 1;
  1358. break;
  1359. }
  1360. case GCSpropagate: {
  1361. if (fast || g->gray == NULL) {
  1362. g->gcstate = GCSenteratomic; /* finish propagate phase */
  1363. work = 0;
  1364. }
  1365. else {
  1366. propagatemark(g); /* traverse one gray object */
  1367. work = 1;
  1368. }
  1369. break;
  1370. }
  1371. case GCSenteratomic: {
  1372. work = atomic(L);
  1373. if (checkmajorminor(L, g))
  1374. entersweep(L);
  1375. break;
  1376. }
  1377. case GCSswpallgc: { /* sweep "regular" objects */
  1378. sweepstep(L, g, GCSswpfinobj, &g->finobj, fast);
  1379. work = GCSWEEPMAX;
  1380. break;
  1381. }
  1382. case GCSswpfinobj: { /* sweep objects with finalizers */
  1383. sweepstep(L, g, GCSswptobefnz, &g->tobefnz, fast);
  1384. work = GCSWEEPMAX;
  1385. break;
  1386. }
  1387. case GCSswptobefnz: { /* sweep objects to be finalized */
  1388. sweepstep(L, g, GCSswpend, NULL, fast);
  1389. work = GCSWEEPMAX;
  1390. break;
  1391. }
  1392. case GCSswpend: { /* finish sweeps */
  1393. checkSizes(L, g);
  1394. g->gcstate = GCScallfin;
  1395. work = 0;
  1396. break;
  1397. }
  1398. case GCScallfin: { /* call finalizers */
  1399. if (g->tobefnz && !g->gcemergency) {
  1400. g->gcstopem = 0; /* ok collections during finalizers */
  1401. GCTM(L); /* call one finalizer */
  1402. work = 1;
  1403. }
  1404. else { /* emergency mode or no more finalizers */
  1405. g->gcstate = GCSpause; /* finish collection */
  1406. work = 0;
  1407. }
  1408. break;
  1409. }
  1410. default: lua_assert(0); return 0;
  1411. }
  1412. g->gcstopem = 0;
  1413. return work;
  1414. }
  1415. /*
  1416. ** Advances the garbage collector until it reaches the given state.
  1417. ** (The option 'fast' is only for testing; in normal code, 'fast'
  1418. ** here is always true.)
  1419. */
  1420. void luaC_runtilstate (lua_State *L, int state, int fast) {
  1421. global_State *g = G(L);
  1422. lua_assert(g->gckind == KGC_INC);
  1423. while (state != g->gcstate)
  1424. singlestep(L, fast);
  1425. }
  1426. /*
  1427. ** Performs a basic incremental step. The debt and step size are
  1428. ** converted from bytes to "units of work"; then the function loops
  1429. ** running single steps until adding that many units of work or
  1430. ** finishing a cycle (pause state). Finally, it sets the debt that
  1431. ** controls when next step will be performed.
  1432. */
  1433. static void incstep (lua_State *L, global_State *g) {
  1434. l_obj stepsize = applygcparam(g, STEPSIZE, 100);
  1435. l_obj work2do = applygcparam(g, STEPMUL, stepsize);
  1436. int fast = 0;
  1437. if (work2do == 0) { /* special case: do a full collection */
  1438. work2do = MAX_LOBJ; /* do unlimited work */
  1439. fast = 1;
  1440. }
  1441. do { /* repeat until pause or enough work */
  1442. l_obj work = singlestep(L, fast); /* perform one single step */
  1443. if (g->gckind == KGC_GENMINOR) /* returned to minor collections? */
  1444. return; /* nothing else to be done here */
  1445. work2do -= work;
  1446. } while (work2do > 0 && g->gcstate != GCSpause);
  1447. if (g->gcstate == GCSpause)
  1448. setpause(g); /* pause until next cycle */
  1449. else
  1450. luaE_setdebt(g, stepsize);
  1451. }
  1452. /*
  1453. ** Performs a basic GC step if collector is running. (If collector is
  1454. ** not running, set a reasonable debt to avoid it being called at
  1455. ** every single check.)
  1456. */
  1457. void luaC_step (lua_State *L) {
  1458. global_State *g = G(L);
  1459. lua_assert(!g->gcemergency);
  1460. if (!gcrunning(g)) /* not running? */
  1461. luaE_setdebt(g, 2000);
  1462. else {
  1463. switch (g->gckind) {
  1464. case KGC_INC: case KGC_GENMAJOR:
  1465. incstep(L, g);
  1466. break;
  1467. case KGC_GENMINOR:
  1468. youngcollection(L, g);
  1469. setminordebt(g);
  1470. break;
  1471. }
  1472. }
  1473. }
  1474. /*
  1475. ** Perform a full collection in incremental mode.
  1476. ** Before running the collection, check 'keepinvariant'; if it is true,
  1477. ** there may be some objects marked as black, so the collector has
  1478. ** to sweep all objects to turn them back to white (as white has not
  1479. ** changed, nothing will be collected).
  1480. */
  1481. static void fullinc (lua_State *L, global_State *g) {
  1482. if (keepinvariant(g)) /* black objects? */
  1483. entersweep(L); /* sweep everything to turn them back to white */
  1484. /* finish any pending sweep phase to start a new cycle */
  1485. luaC_runtilstate(L, GCSpause, 1);
  1486. luaC_runtilstate(L, GCScallfin, 1); /* run up to finalizers */
  1487. /* 'marked' must be correct after a full GC cycle */
  1488. lua_assert(g->marked == gettotalobjs(g));
  1489. luaC_runtilstate(L, GCSpause, 1); /* finish collection */
  1490. setpause(g);
  1491. }
  1492. /*
  1493. ** Performs a full GC cycle; if 'isemergency', set a flag to avoid
  1494. ** some operations which could change the interpreter state in some
  1495. ** unexpected ways (running finalizers and shrinking some structures).
  1496. */
  1497. void luaC_fullgc (lua_State *L, int isemergency) {
  1498. global_State *g = G(L);
  1499. lua_assert(!g->gcemergency);
  1500. g->gcemergency = isemergency; /* set flag */
  1501. switch (g->gckind) {
  1502. case KGC_GENMINOR: fullgen(L, g); break;
  1503. case KGC_INC: fullinc(L, g); break;
  1504. case KGC_GENMAJOR:
  1505. g->gckind = KGC_INC;
  1506. fullinc(L, g);
  1507. g->gckind = KGC_GENMAJOR;
  1508. break;
  1509. }
  1510. g->gcemergency = 0;
  1511. }
  1512. /* }====================================================== */