lgc.c 53 KB

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