lgc.c 56 KB

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