lgc.c 50 KB

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