lgc.c 52 KB

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