lgc.c 54 KB

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