lgc.c 46 KB

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