lgc.c 54 KB

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