lgc.c 47 KB

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