lgc.c 47 KB

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