lgc.c 47 KB

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