2
0

lgc.c 55 KB

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