lgc.c 52 KB

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