lgc.c 48 KB

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