lgc.c 48 KB

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