lgc.c 50 KB

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