lgc.c 47 KB

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