lgc.c 47 KB

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