lgc.c 50 KB

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