lgc.c 48 KB

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