lgc.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  1. /*
  2. ** $Id: lgc.c,v 2.240 2017/11/30 15:37:16 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. static int traversethread (global_State *g, lua_State *th) {
  490. StkId o = th->stack;
  491. if (o == NULL)
  492. return 1; /* stack not completely built yet */
  493. lua_assert(g->gcstate == GCSatomic ||
  494. th->openupval == NULL || isintwups(th));
  495. for (; o < th->top; o++) /* mark live elements in the stack */
  496. markvalue(g, s2v(o));
  497. if (g->gcstate == GCSatomic) { /* final traversal? */
  498. StkId lim = th->stack + th->stacksize; /* real end of stack */
  499. for (; o < lim; o++) /* clear not-marked stack slice */
  500. setnilvalue(s2v(o));
  501. /* 'remarkupvals' may have removed thread from 'twups' list */
  502. if (!isintwups(th) && th->openupval != NULL) {
  503. th->twups = g->twups; /* link it back to the list */
  504. g->twups = th;
  505. }
  506. }
  507. else if (!g->gcemergency)
  508. luaD_shrinkstack(th); /* do not change stack in emergency cycle */
  509. return 1 + th->stacksize;
  510. }
  511. /*
  512. ** traverse one gray object, turning it to black (except for threads,
  513. ** which are always gray).
  514. */
  515. static lu_mem propagatemark (global_State *g) {
  516. GCObject *o = g->gray;
  517. gray2black(o);
  518. switch (o->tt) {
  519. case LUA_TTABLE: {
  520. Table *h = gco2t(o);
  521. g->gray = h->gclist; /* remove from 'gray' list */
  522. return traversetable(g, h);
  523. }
  524. case LUA_TLCL: {
  525. LClosure *cl = gco2lcl(o);
  526. g->gray = cl->gclist; /* remove from 'gray' list */
  527. return traverseLclosure(g, cl);
  528. }
  529. case LUA_TCCL: {
  530. CClosure *cl = gco2ccl(o);
  531. g->gray = cl->gclist; /* remove from 'gray' list */
  532. return traverseCclosure(g, cl);
  533. }
  534. case LUA_TTHREAD: {
  535. lua_State *th = gco2th(o);
  536. g->gray = th->gclist; /* remove from 'gray' list */
  537. linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
  538. black2gray(o);
  539. return traversethread(g, th);
  540. }
  541. case LUA_TPROTO: {
  542. Proto *p = gco2p(o);
  543. g->gray = p->gclist; /* remove from 'gray' list */
  544. return traverseproto(g, p);
  545. }
  546. default: lua_assert(0); return 0;
  547. }
  548. }
  549. static lu_mem propagateall (global_State *g) {
  550. lu_mem tot = 0;
  551. while (g->gray)
  552. tot += propagatemark(g);
  553. return tot;
  554. }
  555. static void convergeephemerons (global_State *g) {
  556. int changed;
  557. do {
  558. GCObject *w;
  559. GCObject *next = g->ephemeron; /* get ephemeron list */
  560. g->ephemeron = NULL; /* tables may return to this list when traversed */
  561. changed = 0;
  562. while ((w = next) != NULL) {
  563. next = gco2t(w)->gclist;
  564. if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */
  565. propagateall(g); /* propagate changes */
  566. changed = 1; /* will have to revisit all ephemeron tables */
  567. }
  568. }
  569. } while (changed);
  570. }
  571. /* }====================================================== */
  572. /*
  573. ** {======================================================
  574. ** Sweep Functions
  575. ** =======================================================
  576. */
  577. static void clearprotolist (global_State *g) {
  578. GCObject *p = g->protogray;
  579. g->protogray = NULL;
  580. while (p != NULL) {
  581. Proto *pp = gco2p(p);
  582. GCObject *next = pp->gclist;
  583. lua_assert(isgray(pp) && (pp->cache != NULL || pp->cachemiss >= MAXMISS));
  584. gray2black(pp);
  585. checkprotocache(g, pp);
  586. p = next;
  587. }
  588. }
  589. /*
  590. ** clear entries with unmarked keys from all weaktables in list 'l'
  591. */
  592. static void clearkeys (global_State *g, GCObject *l) {
  593. for (; l; l = gco2t(l)->gclist) {
  594. Table *h = gco2t(l);
  595. Node *n, *limit = gnodelast(h);
  596. for (n = gnode(h, 0); n < limit; n++) {
  597. if (!ttisnil(gval(n)) && (iscleared(g, gckeyN(n)))) /* unmarked key? */
  598. setnilvalue(gval(n)); /* clear value */
  599. if (ttisnil(gval(n))) /* is entry empty? */
  600. removeentry(n); /* remove it from table */
  601. }
  602. }
  603. }
  604. /*
  605. ** clear entries with unmarked values from all weaktables in list 'l' up
  606. ** to element 'f'
  607. */
  608. static void clearvalues (global_State *g, GCObject *l, GCObject *f) {
  609. for (; l != f; l = gco2t(l)->gclist) {
  610. Table *h = gco2t(l);
  611. Node *n, *limit = gnodelast(h);
  612. unsigned int i;
  613. for (i = 0; i < h->sizearray; i++) {
  614. TValue *o = &h->array[i];
  615. if (iscleared(g, gcvalueN(o))) /* value was collected? */
  616. setnilvalue(o); /* remove value */
  617. }
  618. for (n = gnode(h, 0); n < limit; n++) {
  619. if (iscleared(g, gcvalueN(gval(n)))) /* unmarked value? */
  620. setnilvalue(gval(n)); /* clear value */
  621. if (ttisnil(gval(n))) /* is entry empty? */
  622. removeentry(n); /* remove it from table */
  623. }
  624. }
  625. }
  626. static void freeupval (lua_State *L, UpVal *uv) {
  627. if (upisopen(uv))
  628. luaF_unlinkupval(uv);
  629. luaM_free(L, uv);
  630. }
  631. static void freeobj (lua_State *L, GCObject *o) {
  632. switch (o->tt) {
  633. case LUA_TPROTO:
  634. luaF_freeproto(L, gco2p(o));
  635. break;
  636. case LUA_TUPVAL:
  637. freeupval(L, gco2upv(o));
  638. break;
  639. case LUA_TLCL:
  640. luaM_freemem(L, o, sizeLclosure(gco2lcl(o)->nupvalues));
  641. break;
  642. case LUA_TCCL:
  643. luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));
  644. break;
  645. case LUA_TTABLE:
  646. luaH_free(L, gco2t(o));
  647. break;
  648. case LUA_TTHREAD:
  649. luaE_freethread(L, gco2th(o));
  650. break;
  651. case LUA_TUSERDATA:
  652. luaM_freemem(L, o, sizeudata(gco2u(o)));
  653. break;
  654. case LUA_TSHRSTR:
  655. luaS_remove(L, gco2ts(o)); /* remove it from hash table */
  656. luaM_freemem(L, o, sizelstring(gco2ts(o)->shrlen));
  657. break;
  658. case LUA_TLNGSTR:
  659. luaM_freemem(L, o, sizelstring(gco2ts(o)->u.lnglen));
  660. break;
  661. default: lua_assert(0);
  662. }
  663. }
  664. /*
  665. ** sweep at most 'countin' elements from a list of GCObjects erasing dead
  666. ** objects, where a dead object is one marked with the old (non current)
  667. ** white; change all non-dead objects back to white, preparing for next
  668. ** collection cycle. Return where to continue the traversal or NULL if
  669. ** list is finished. ('*countout' gets the number of elements traversed.)
  670. */
  671. static GCObject **sweeplist (lua_State *L, GCObject **p, int countin,
  672. int *countout) {
  673. global_State *g = G(L);
  674. int ow = otherwhite(g);
  675. int i;
  676. int white = luaC_white(g); /* current white */
  677. for (i = 0; *p != NULL && i < countin; i++) {
  678. GCObject *curr = *p;
  679. int marked = curr->marked;
  680. if (isdeadm(ow, marked)) { /* is 'curr' dead? */
  681. *p = curr->next; /* remove 'curr' from list */
  682. freeobj(L, curr); /* erase 'curr' */
  683. }
  684. else { /* change mark to 'white' */
  685. curr->marked = cast_byte((marked & maskcolors) | white);
  686. p = &curr->next; /* go to next element */
  687. }
  688. }
  689. if (countout)
  690. *countout = i; /* number of elements traversed */
  691. return (*p == NULL) ? NULL : p;
  692. }
  693. /*
  694. ** sweep a list until a live object (or end of list)
  695. */
  696. static GCObject **sweeptolive (lua_State *L, GCObject **p) {
  697. GCObject **old = p;
  698. do {
  699. p = sweeplist(L, p, 1, NULL);
  700. } while (p == old);
  701. return p;
  702. }
  703. /* }====================================================== */
  704. /*
  705. ** {======================================================
  706. ** Finalization
  707. ** =======================================================
  708. */
  709. /*
  710. ** If possible, shrink string table (protected from memory errors).
  711. */
  712. static void shrinkstrtable (lua_State *L, void *ud) {
  713. luaS_resize(L, *cast(int*, ud) / 2);
  714. }
  715. static void checkSizes (lua_State *L, global_State *g) {
  716. if (!g->gcemergency) {
  717. l_mem olddebt = g->GCdebt;
  718. if (g->strt.nuse < g->strt.size / 4) /* string table too big? */
  719. luaD_rawrunprotected(L, &shrinkstrtable, &g->strt.size);
  720. g->GCestimate += g->GCdebt - olddebt; /* correct estimate */
  721. }
  722. }
  723. /*
  724. ** Get the next udata to be finalized from the 'tobefnz' list, and
  725. ** link it back into the 'allgc' list.
  726. */
  727. static GCObject *udata2finalize (global_State *g) {
  728. GCObject *o = g->tobefnz; /* get first element */
  729. lua_assert(tofinalize(o));
  730. g->tobefnz = o->next; /* remove it from 'tobefnz' list */
  731. o->next = g->allgc; /* return it to 'allgc' list */
  732. g->allgc = o;
  733. resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */
  734. if (issweepphase(g))
  735. makewhite(g, o); /* "sweep" object */
  736. return o;
  737. }
  738. static void dothecall (lua_State *L, void *ud) {
  739. UNUSED(ud);
  740. luaD_callnoyield(L, L->top - 2, 0);
  741. }
  742. static void GCTM (lua_State *L, int propagateerrors) {
  743. global_State *g = G(L);
  744. const TValue *tm;
  745. TValue v;
  746. setgcovalue(L, &v, udata2finalize(g));
  747. tm = luaT_gettmbyobj(L, &v, TM_GC);
  748. if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */
  749. int status;
  750. lu_byte oldah = L->allowhook;
  751. int running = g->gcrunning;
  752. L->allowhook = 0; /* stop debug hooks during GC metamethod */
  753. g->gcrunning = 0; /* avoid GC steps */
  754. setobj2s(L, L->top, tm); /* push finalizer... */
  755. setobj2s(L, L->top + 1, &v); /* ... and its argument */
  756. L->top += 2; /* and (next line) call the finalizer */
  757. L->ci->callstatus |= CIST_FIN; /* will run a finalizer */
  758. status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
  759. L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */
  760. L->allowhook = oldah; /* restore hooks */
  761. g->gcrunning = running; /* restore state */
  762. if (status != LUA_OK && propagateerrors) { /* error while running __gc? */
  763. if (status == LUA_ERRRUN) { /* is there an error object? */
  764. const char *msg = (ttisstring(s2v(L->top - 1)))
  765. ? svalue(s2v(L->top - 1))
  766. : "no message";
  767. luaO_pushfstring(L, "error in __gc metamethod (%s)", msg);
  768. status = LUA_ERRGCMM; /* error in __gc metamethod */
  769. }
  770. luaD_throw(L, status); /* re-throw error */
  771. }
  772. }
  773. }
  774. /*
  775. ** Call a few finalizers
  776. */
  777. static int runafewfinalizers (lua_State *L, int n) {
  778. global_State *g = G(L);
  779. int i;
  780. for (i = 0; i < n && g->tobefnz; i++)
  781. GCTM(L, 1); /* call one finalizer */
  782. return i;
  783. }
  784. /*
  785. ** call all pending finalizers
  786. */
  787. static void callallpendingfinalizers (lua_State *L) {
  788. global_State *g = G(L);
  789. while (g->tobefnz)
  790. GCTM(L, 0);
  791. }
  792. /*
  793. ** find last 'next' field in list 'p' list (to add elements in its end)
  794. */
  795. static GCObject **findlast (GCObject **p) {
  796. while (*p != NULL)
  797. p = &(*p)->next;
  798. return p;
  799. }
  800. /*
  801. ** Move all unreachable objects (or 'all' objects) that need
  802. ** finalization from list 'finobj' to list 'tobefnz' (to be finalized).
  803. ** (Note that objects after 'finobjold' cannot be white, so they
  804. ** don't need to be traversed. In incremental mode, 'finobjold' is NULL,
  805. ** so the whole list is traversed.)
  806. */
  807. static void separatetobefnz (global_State *g, int all) {
  808. GCObject *curr;
  809. GCObject **p = &g->finobj;
  810. GCObject **lastnext = findlast(&g->tobefnz);
  811. while ((curr = *p) != g->finobjold) { /* traverse all finalizable objects */
  812. lua_assert(tofinalize(curr));
  813. if (!(iswhite(curr) || all)) /* not being collected? */
  814. p = &curr->next; /* don't bother with it */
  815. else {
  816. if (curr == g->finobjsur) /* removing 'finobjsur'? */
  817. g->finobjsur = curr->next; /* correct it */
  818. *p = curr->next; /* remove 'curr' from 'finobj' list */
  819. curr->next = *lastnext; /* link at the end of 'tobefnz' list */
  820. *lastnext = curr;
  821. lastnext = &curr->next;
  822. }
  823. }
  824. }
  825. /*
  826. ** if object 'o' has a finalizer, remove it from 'allgc' list (must
  827. ** search the list to find it) and link it in 'finobj' list.
  828. */
  829. void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
  830. global_State *g = G(L);
  831. if (tofinalize(o) || /* obj. is already marked... */
  832. gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */
  833. return; /* nothing to be done */
  834. else { /* move 'o' to 'finobj' list */
  835. GCObject **p;
  836. if (issweepphase(g)) {
  837. makewhite(g, o); /* "sweep" object 'o' */
  838. if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */
  839. g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */
  840. }
  841. else { /* correct pointers into 'allgc' list, if needed */
  842. if (o == g->survival)
  843. g->survival = o->next;
  844. if (o == g->old)
  845. g->old = o->next;
  846. if (o == g->reallyold)
  847. g->reallyold = o->next;
  848. }
  849. /* search for pointer pointing to 'o' */
  850. for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
  851. *p = o->next; /* remove 'o' from 'allgc' list */
  852. o->next = g->finobj; /* link it in 'finobj' list */
  853. g->finobj = o;
  854. l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */
  855. }
  856. }
  857. /* }====================================================== */
  858. /*
  859. ** {======================================================
  860. ** Generational Collector
  861. ** =======================================================
  862. */
  863. /* mask to erase all color bits, not changing gen-related stuff */
  864. #define maskgencolors (~(bitmask(BLACKBIT) | WHITEBITS))
  865. /*
  866. ** Sweep a list of objects, deleting dead ones and turning
  867. ** the non dead to old (without changing their colors).
  868. */
  869. static void sweep2old (lua_State *L, GCObject **p) {
  870. GCObject *curr;
  871. while ((curr = *p) != NULL) {
  872. if (iswhite(curr)) { /* is 'curr' dead? */
  873. lua_assert(isdead(G(L), curr));
  874. *p = curr->next; /* remove 'curr' from list */
  875. freeobj(L, curr); /* erase 'curr' */
  876. }
  877. else { /* all surviving objects become old */
  878. setage(curr, G_OLD);
  879. p = &curr->next; /* go to next element */
  880. }
  881. }
  882. }
  883. /*
  884. ** Sweep for generational mode. Delete dead objects. (Because the
  885. ** collection is not incremental, there are no "new white" objects
  886. ** during the sweep. So, any white object must be dead.) For
  887. ** non-dead objects, advance their ages and clear the color of
  888. ** new objects. (Old objects keep their colors.)
  889. */
  890. static GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p,
  891. GCObject *limit) {
  892. static lu_byte nextage[] = {
  893. G_SURVIVAL, /* from G_NEW */
  894. G_OLD1, /* from G_SURVIVAL */
  895. G_OLD1, /* from G_OLD0 */
  896. G_OLD, /* from G_OLD1 */
  897. G_OLD, /* from G_OLD (do not change) */
  898. G_TOUCHED1, /* from G_TOUCHED1 (do not change) */
  899. G_TOUCHED2 /* from G_TOUCHED2 (do not change) */
  900. };
  901. int white = luaC_white(g);
  902. GCObject *curr;
  903. while ((curr = *p) != limit) {
  904. if (iswhite(curr)) { /* is 'curr' dead? */
  905. lua_assert(!isold(curr) && isdead(g, curr));
  906. *p = curr->next; /* remove 'curr' from list */
  907. freeobj(L, curr); /* erase 'curr' */
  908. }
  909. else { /* correct mark and age */
  910. if (getage(curr) == G_NEW)
  911. curr->marked = cast_byte((curr->marked & maskgencolors) | white);
  912. setage(curr, nextage[getage(curr)]);
  913. p = &curr->next; /* go to next element */
  914. }
  915. }
  916. return p;
  917. }
  918. /*
  919. ** Traverse a list making all its elements white and clearing their
  920. ** age.
  921. */
  922. static void whitelist (global_State *g, GCObject *p) {
  923. int white = luaC_white(g);
  924. for (; p != NULL; p = p->next)
  925. p->marked = cast_byte((p->marked & maskcolors) | white);
  926. }
  927. /*
  928. ** Correct a list of gray objects. Because this correction is
  929. ** done after sweeping, young objects can be white and still
  930. ** be in the list. They are only removed.
  931. ** For tables, advance 'touched1' to 'touched2'; 'touched2' objects
  932. ** become regular old and are removed from the list.
  933. ** For threads, just remove white ones from the list.
  934. */
  935. static GCObject **correctgraylist (GCObject **p) {
  936. GCObject *curr;
  937. while ((curr = *p) != NULL) {
  938. switch (curr->tt) {
  939. case LUA_TTABLE: {
  940. Table *h = gco2t(curr);
  941. if (getage(h) == G_TOUCHED1) { /* touched in this cycle? */
  942. lua_assert(isgray(h));
  943. gray2black(h); /* make it black, for next barrier */
  944. changeage(h, G_TOUCHED1, G_TOUCHED2);
  945. p = &h->gclist; /* go to next element */
  946. }
  947. else {
  948. if (!iswhite(h)) {
  949. lua_assert(isold(h));
  950. if (getage(h) == G_TOUCHED2)
  951. changeage(h, G_TOUCHED2, G_OLD);
  952. gray2black(h); /* make it black */
  953. }
  954. *p = h->gclist; /* remove 'curr' from gray list */
  955. }
  956. break;
  957. }
  958. case LUA_TTHREAD: {
  959. lua_State *th = gco2th(curr);
  960. lua_assert(!isblack(th));
  961. if (iswhite(th)) /* new object? */
  962. *p = th->gclist; /* remove from gray list */
  963. else /* old threads remain gray */
  964. p = &th->gclist; /* go to next element */
  965. break;
  966. }
  967. default: lua_assert(0); /* nothing more could be gray here */
  968. }
  969. }
  970. return p;
  971. }
  972. /*
  973. ** Correct all gray lists, coalescing them into 'grayagain'.
  974. */
  975. static void correctgraylists (global_State *g) {
  976. GCObject **list = correctgraylist(&g->grayagain);
  977. *list = g->weak; g->weak = NULL;
  978. list = correctgraylist(list);
  979. *list = g->allweak; g->allweak = NULL;
  980. list = correctgraylist(list);
  981. *list = g->ephemeron; g->ephemeron = NULL;
  982. correctgraylist(list);
  983. }
  984. /*
  985. ** Mark 'old1' objects when starting a new young collection.
  986. ** Gray objects are already in some gray list, and so will be visited
  987. ** in the atomic step.
  988. */
  989. static void markold (global_State *g, GCObject *from, GCObject *to) {
  990. GCObject *p;
  991. for (p = from; p != to; p = p->next) {
  992. if (getage(p) == G_OLD1) {
  993. lua_assert(!iswhite(p));
  994. if (isblack(p)) {
  995. black2gray(p); /* should be '2white', but gray works too */
  996. reallymarkobject(g, p);
  997. }
  998. }
  999. }
  1000. }
  1001. /*
  1002. ** Finish a young-generation collection.
  1003. */
  1004. static void finishgencycle (lua_State *L, global_State *g) {
  1005. correctgraylists(g);
  1006. checkSizes(L, g);
  1007. g->gcstate = GCSpropagate; /* skip restart */
  1008. callallpendingfinalizers(L);
  1009. }
  1010. /*
  1011. ** Does a young collection. First, mark 'old1' objects. (Only survival
  1012. ** and "recent old" lists can contain 'old1' objects. New lists cannot
  1013. ** contain 'old1' objects, at most 'old0' objects that were already
  1014. ** visited when marked old.) Then does the atomic step. Then,
  1015. ** sweep all lists and advance pointers. Finally, finish the collection.
  1016. */
  1017. static void youngcollection (lua_State *L, global_State *g) {
  1018. GCObject **psurvival; /* to point to first non-dead survival object */
  1019. lua_assert(g->gcstate == GCSpropagate);
  1020. markold(g, g->survival, g->reallyold);
  1021. markold(g, g->finobj, g->finobjrold);
  1022. atomic(L);
  1023. /* sweep nursery and get a pointer to its last live element */
  1024. psurvival = sweepgen(L, g, &g->allgc, g->survival);
  1025. /* sweep 'survival' and 'old' */
  1026. sweepgen(L, g, psurvival, g->reallyold);
  1027. g->reallyold = g->old;
  1028. g->old = *psurvival; /* 'survival' survivals are old now */
  1029. g->survival = g->allgc; /* all news are survivals */
  1030. /* repeat for 'finobj' lists */
  1031. psurvival = sweepgen(L, g, &g->finobj, g->finobjsur);
  1032. /* sweep 'survival' and 'old' */
  1033. sweepgen(L, g, psurvival, g->finobjrold);
  1034. g->finobjrold = g->finobjold;
  1035. g->finobjold = *psurvival; /* 'survival' survivals are old now */
  1036. g->finobjsur = g->finobj; /* all news are survivals */
  1037. sweepgen(L, g, &g->tobefnz, NULL);
  1038. finishgencycle(L, g);
  1039. }
  1040. /*
  1041. ** Enter generational mode. Must go until the end of an atomic cycle
  1042. ** to ensure that all threads are in the gray list. Then, turn all
  1043. ** objects into old and finishes the collection.
  1044. */
  1045. static void entergen (lua_State *L, global_State *g) {
  1046. luaC_runtilstate(L, bitmask(GCSpause)); /* prepare to start a new cycle */
  1047. luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */
  1048. atomic(L);
  1049. /* sweep all elements making them old */
  1050. sweep2old(L, &g->allgc);
  1051. /* everything alive now is old */
  1052. g->reallyold = g->old = g->survival = g->allgc;
  1053. /* repeat for 'finobj' lists */
  1054. sweep2old(L, &g->finobj);
  1055. g->finobjrold = g->finobjold = g->finobjsur = g->finobj;
  1056. sweep2old(L, &g->tobefnz);
  1057. finishgencycle(L, g);
  1058. g->gckind = KGC_GEN;
  1059. g->GCestimate = gettotalbytes(g); /* base for memory control */
  1060. }
  1061. /*
  1062. ** Enter incremental mode. Turn all objects white, make all
  1063. ** intermediate lists point to NULL (to avoid invalid pointers),
  1064. ** and go to pause state.
  1065. */
  1066. static void enterinc (global_State *g) {
  1067. whitelist(g, g->allgc);
  1068. g->reallyold = g->old = g->survival = NULL;
  1069. whitelist(g, g->finobj);
  1070. g->finobjrold = g->finobjold = g->finobjsur = NULL;
  1071. lua_assert(g->tobefnz == NULL); /* no need to sweep */
  1072. g->gcstate = GCSpause;
  1073. g->gckind = KGC_INC;
  1074. }
  1075. /*
  1076. ** Change collector mode to 'newmode'.
  1077. */
  1078. void luaC_changemode (lua_State *L, int newmode) {
  1079. global_State *g = G(L);
  1080. if (newmode != g->gckind) {
  1081. if (newmode == KGC_GEN) /* entering generational mode? */
  1082. entergen(L, g);
  1083. else
  1084. enterinc(g); /* entering incremental mode */
  1085. }
  1086. }
  1087. /*
  1088. ** Does a full collection in generational mode.
  1089. */
  1090. static void fullgen (lua_State *L, global_State *g) {
  1091. enterinc(g);
  1092. entergen(L, g);
  1093. }
  1094. /*
  1095. ** Does a generational "step". If memory grows 'genmajormul'% larger
  1096. ** than last major collection (kept in 'g->GCestimate'), does a major
  1097. ** collection. Otherwise, does a minor collection and set debt to make
  1098. ** another collection when memory grows 'genminormul'% larger.
  1099. ** 'GCdebt <= 0' means an explicit call to GC step with "size" zero;
  1100. ** in that case, always do a minor collection.
  1101. */
  1102. static void genstep (lua_State *L, global_State *g) {
  1103. lu_mem majorbase = g->GCestimate;
  1104. int majormul = getgcparam(g->genmajormul);
  1105. if (g->GCdebt > 0 &&
  1106. gettotalbytes(g) > (majorbase / 100) * (100 + majormul)) {
  1107. fullgen(L, g);
  1108. }
  1109. else {
  1110. lu_mem mem;
  1111. youngcollection(L, g);
  1112. mem = gettotalbytes(g);
  1113. luaE_setdebt(g, -(cast(l_mem, (mem / 100)) * g->genminormul));
  1114. g->GCestimate = majorbase; /* preserve base value */
  1115. }
  1116. }
  1117. /* }====================================================== */
  1118. /*
  1119. ** {======================================================
  1120. ** GC control
  1121. ** =======================================================
  1122. */
  1123. /*
  1124. ** Set the "time" to wait before starting a new GC cycle; cycle will
  1125. ** start when memory use hits the threshold of ('estimate' * pause /
  1126. ** PAUSEADJ). (Division by 'estimate' should be OK: it cannot be zero,
  1127. ** because Lua cannot even start with less than PAUSEADJ bytes).
  1128. */
  1129. static void setpause (global_State *g) {
  1130. l_mem threshold, debt;
  1131. int pause = getgcparam(g->gcpause);
  1132. l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */
  1133. lua_assert(estimate > 0);
  1134. threshold = (pause < MAX_LMEM / estimate) /* overflow? */
  1135. ? estimate * pause /* no overflow */
  1136. : MAX_LMEM; /* overflow; truncate to maximum */
  1137. debt = gettotalbytes(g) - threshold;
  1138. if (debt > 0) debt = 0;
  1139. luaE_setdebt(g, debt);
  1140. }
  1141. /*
  1142. ** Enter first sweep phase.
  1143. ** The call to 'sweeptolive' makes the pointer point to an object
  1144. ** inside the list (instead of to the header), so that the real sweep do
  1145. ** not need to skip objects created between "now" and the start of the
  1146. ** real sweep.
  1147. */
  1148. static void entersweep (lua_State *L) {
  1149. global_State *g = G(L);
  1150. g->gcstate = GCSswpallgc;
  1151. lua_assert(g->sweepgc == NULL);
  1152. g->sweepgc = sweeptolive(L, &g->allgc);
  1153. }
  1154. /*
  1155. ** Delete all objects in list 'p' until (but not including) object
  1156. ** 'limit'.
  1157. */
  1158. static void deletelist (lua_State *L, GCObject *p, GCObject *limit) {
  1159. while (p != limit) {
  1160. GCObject *next = p->next;
  1161. freeobj(L, p);
  1162. p = next;
  1163. }
  1164. }
  1165. /*
  1166. ** Call all finalizers of the objects in the given Lua state, and
  1167. ** then free all objects, except for the main thread.
  1168. */
  1169. void luaC_freeallobjects (lua_State *L) {
  1170. global_State *g = G(L);
  1171. luaC_changemode(L, KGC_INC);
  1172. separatetobefnz(g, 1); /* separate all objects with finalizers */
  1173. lua_assert(g->finobj == NULL);
  1174. callallpendingfinalizers(L);
  1175. deletelist(L, g->allgc, obj2gco(g->mainthread));
  1176. deletelist(L, g->finobj, NULL);
  1177. deletelist(L, g->fixedgc, NULL); /* collect fixed objects */
  1178. lua_assert(g->strt.nuse == 0);
  1179. }
  1180. static lu_mem atomic (lua_State *L) {
  1181. global_State *g = G(L);
  1182. lu_mem work = 0;
  1183. GCObject *origweak, *origall;
  1184. GCObject *grayagain = g->grayagain; /* save original list */
  1185. g->grayagain = NULL;
  1186. lua_assert(g->ephemeron == NULL && g->weak == NULL);
  1187. lua_assert(!iswhite(g->mainthread));
  1188. g->gcstate = GCSatomic;
  1189. markobject(g, L); /* mark running thread */
  1190. /* registry and global metatables may be changed by API */
  1191. markvalue(g, &g->l_registry);
  1192. markmt(g); /* mark global metatables */
  1193. /* remark occasional upvalues of (maybe) dead threads */
  1194. work += remarkupvals(g);
  1195. work += propagateall(g); /* propagate changes */
  1196. g->gray = grayagain;
  1197. work += propagateall(g); /* traverse 'grayagain' list */
  1198. convergeephemerons(g);
  1199. /* at this point, all strongly accessible objects are marked. */
  1200. /* Clear values from weak tables, before checking finalizers */
  1201. clearvalues(g, g->weak, NULL);
  1202. clearvalues(g, g->allweak, NULL);
  1203. origweak = g->weak; origall = g->allweak;
  1204. separatetobefnz(g, 0); /* separate objects to be finalized */
  1205. work += markbeingfnz(g); /* mark objects that will be finalized */
  1206. work += propagateall(g); /* remark, to propagate 'resurrection' */
  1207. convergeephemerons(g);
  1208. /* at this point, all resurrected objects are marked. */
  1209. /* remove dead objects from weak tables */
  1210. clearkeys(g, g->ephemeron); /* clear keys from all ephemeron tables */
  1211. clearkeys(g, g->allweak); /* clear keys from all 'allweak' tables */
  1212. /* clear values from resurrected weak tables */
  1213. clearvalues(g, g->weak, origweak);
  1214. clearvalues(g, g->allweak, origall);
  1215. luaS_clearcache(g);
  1216. clearprotolist(g);
  1217. g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
  1218. lua_assert(g->gray == NULL);
  1219. return work; /* estimate of slots marked by 'atomic' */
  1220. }
  1221. static int sweepstep (lua_State *L, global_State *g,
  1222. int nextstate, GCObject **nextlist) {
  1223. if (g->sweepgc) {
  1224. l_mem olddebt = g->GCdebt;
  1225. int count;
  1226. g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX, &count);
  1227. g->GCestimate += g->GCdebt - olddebt; /* update estimate */
  1228. return count;
  1229. }
  1230. else { /* enter next state */
  1231. g->gcstate = nextstate;
  1232. g->sweepgc = nextlist;
  1233. return 0; /* no work done */
  1234. }
  1235. }
  1236. static lu_mem singlestep (lua_State *L) {
  1237. global_State *g = G(L);
  1238. switch (g->gcstate) {
  1239. case GCSpause: {
  1240. restartcollection(g);
  1241. g->gcstate = GCSpropagate;
  1242. return 1;
  1243. }
  1244. case GCSpropagate: {
  1245. if (g->gray == NULL) { /* no more gray objects? */
  1246. g->gcstate = GCSenteratomic; /* finish propagate phase */
  1247. return 0;
  1248. }
  1249. else
  1250. return propagatemark(g); /* traverse one gray object */
  1251. }
  1252. case GCSenteratomic: {
  1253. lu_mem work = propagateall(g); /* make sure gray list is empty */
  1254. work += atomic(L); /* work is what was traversed by 'atomic' */
  1255. entersweep(L);
  1256. g->GCestimate = gettotalbytes(g); /* first estimate */;
  1257. return work;
  1258. }
  1259. case GCSswpallgc: { /* sweep "regular" objects */
  1260. return sweepstep(L, g, GCSswpfinobj, &g->finobj);
  1261. }
  1262. case GCSswpfinobj: { /* sweep objects with finalizers */
  1263. return sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
  1264. }
  1265. case GCSswptobefnz: { /* sweep objects to be finalized */
  1266. return sweepstep(L, g, GCSswpend, NULL);
  1267. }
  1268. case GCSswpend: { /* finish sweeps */
  1269. checkSizes(L, g);
  1270. g->gcstate = GCScallfin;
  1271. return 0;
  1272. }
  1273. case GCScallfin: { /* call remaining finalizers */
  1274. if (g->tobefnz && !g->gcemergency) {
  1275. int n = runafewfinalizers(L, GCFINMAX);
  1276. return n * GCFINALIZECOST;
  1277. }
  1278. else { /* emergency mode or no more finalizers */
  1279. g->gcstate = GCSpause; /* finish collection */
  1280. return 0;
  1281. }
  1282. }
  1283. default: lua_assert(0); return 0;
  1284. }
  1285. }
  1286. /*
  1287. ** advances the garbage collector until it reaches a state allowed
  1288. ** by 'statemask'
  1289. */
  1290. void luaC_runtilstate (lua_State *L, int statesmask) {
  1291. global_State *g = G(L);
  1292. while (!testbit(statesmask, g->gcstate))
  1293. singlestep(L);
  1294. }
  1295. /*
  1296. ** Performs a basic incremental step. The debt and step size are
  1297. ** converted from bytes to "units of work"; then the function loops
  1298. ** running single steps until adding that many units of work or
  1299. ** finishing a cycle (pause state). Finally, it sets the debt that
  1300. ** controls when next step will be performed.
  1301. */
  1302. static void incstep (lua_State *L, global_State *g) {
  1303. int stepmul = (getgcparam(g->gcstepmul) | 1); /* avoid division by 0 */
  1304. l_mem debt = (g->GCdebt / WORK2MEM) * stepmul;
  1305. l_mem stepsize = (g->gcstepsize <= log2maxs(l_mem))
  1306. ? ((cast(l_mem, 1) << g->gcstepsize) / WORK2MEM) * stepmul
  1307. : MAX_LMEM; /* overflow; keep maximum value */
  1308. do { /* repeat until pause or enough "credit" (negative debt) */
  1309. lu_mem work = singlestep(L); /* perform one single step */
  1310. debt -= work;
  1311. } while (debt > -stepsize && g->gcstate != GCSpause);
  1312. if (g->gcstate == GCSpause)
  1313. setpause(g); /* pause until next cycle */
  1314. else {
  1315. debt = (debt / stepmul) * WORK2MEM; /* convert 'work units' to bytes */
  1316. luaE_setdebt(g, debt);
  1317. }
  1318. }
  1319. /*
  1320. ** performs a basic GC step if collector is running
  1321. */
  1322. void luaC_step (lua_State *L) {
  1323. global_State *g = G(L);
  1324. if (g->gcrunning) { /* running? */
  1325. if (g->gckind == KGC_INC)
  1326. incstep(L, g);
  1327. else
  1328. genstep(L, g);
  1329. }
  1330. }
  1331. /*
  1332. ** Perform a full collection in incremental mode.
  1333. ** Before running the collection, check 'keepinvariant'; if it is true,
  1334. ** there may be some objects marked as black, so the collector has
  1335. ** to sweep all objects to turn them back to white (as white has not
  1336. ** changed, nothing will be collected).
  1337. */
  1338. static void fullinc (lua_State *L, global_State *g) {
  1339. if (keepinvariant(g)) /* black objects? */
  1340. entersweep(L); /* sweep everything to turn them back to white */
  1341. /* finish any pending sweep phase to start a new cycle */
  1342. luaC_runtilstate(L, bitmask(GCSpause));
  1343. luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */
  1344. /* estimate must be correct after a full GC cycle */
  1345. lua_assert(g->GCestimate == gettotalbytes(g));
  1346. luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */
  1347. setpause(g);
  1348. }
  1349. /*
  1350. ** Performs a full GC cycle; if 'isemergency', set a flag to avoid
  1351. ** some operations which could change the interpreter state in some
  1352. ** unexpected ways (running finalizers and shrinking some structures).
  1353. */
  1354. void luaC_fullgc (lua_State *L, int isemergency) {
  1355. global_State *g = G(L);
  1356. lua_assert(!g->gcemergency);
  1357. g->gcemergency = isemergency; /* set flag */
  1358. if (g->gckind == KGC_INC)
  1359. fullinc(L, g);
  1360. else
  1361. fullgen(L, g);
  1362. g->gcemergency = 0;
  1363. }
  1364. /* }====================================================== */