lgc.c 48 KB

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