lgc.c 47 KB

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