lgc.c 52 KB

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