lgc.c 54 KB

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