lgc.c 52 KB

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