lgc.c 47 KB

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