2
0

lgc.c 55 KB

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