lgc.c 55 KB

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