lgc.c 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743
  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) && iswhite(gcvalue(x)))
  59. #define keyiswhite(n) (keyiscollectable(n) && iswhite(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 (iswhite(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 iswhite(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));
  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. TString *smode;
  457. markobjectN(g, h->metatable);
  458. if (mode && ttisshrstring(mode) && /* is there a weak mode? */
  459. (cast_void(smode = tsvalue(mode)),
  460. cast_void(weakkey = strchr(getshrstr(smode), 'k')),
  461. cast_void(weakvalue = strchr(getshrstr(smode), 'v')),
  462. (weakkey || weakvalue))) { /* is really weak? */
  463. if (!weakkey) /* strong keys? */
  464. traverseweakvalue(g, h);
  465. else if (!weakvalue) /* strong values? */
  466. traverseephemeron(g, h, 0);
  467. else /* all weak */
  468. linkgclist(h, g->allweak); /* nothing to traverse now */
  469. }
  470. else /* not weak */
  471. traversestrongtable(g, h);
  472. return 1 + h->alimit + 2 * allocsizenode(h);
  473. }
  474. static int traverseudata (global_State *g, Udata *u) {
  475. int i;
  476. markobjectN(g, u->metatable); /* mark its metatable */
  477. for (i = 0; i < u->nuvalue; i++)
  478. markvalue(g, &u->uv[i].uv);
  479. genlink(g, obj2gco(u));
  480. return 1 + u->nuvalue;
  481. }
  482. /*
  483. ** Traverse a prototype. (While a prototype is being build, its
  484. ** arrays can be larger than needed; the extra slots are filled with
  485. ** NULL, so the use of 'markobjectN')
  486. */
  487. static int traverseproto (global_State *g, Proto *f) {
  488. int i;
  489. markobjectN(g, f->source);
  490. for (i = 0; i < f->sizek; i++) /* mark literals */
  491. markvalue(g, &f->k[i]);
  492. for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
  493. markobjectN(g, f->upvalues[i].name);
  494. for (i = 0; i < f->sizep; i++) /* mark nested protos */
  495. markobjectN(g, f->p[i]);
  496. for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
  497. markobjectN(g, f->locvars[i].varname);
  498. return 1 + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars;
  499. }
  500. static int traverseCclosure (global_State *g, CClosure *cl) {
  501. int i;
  502. for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */
  503. markvalue(g, &cl->upvalue[i]);
  504. return 1 + cl->nupvalues;
  505. }
  506. /*
  507. ** Traverse a Lua closure, marking its prototype and its upvalues.
  508. ** (Both can be NULL while closure is being created.)
  509. */
  510. static int traverseLclosure (global_State *g, LClosure *cl) {
  511. int i;
  512. markobjectN(g, cl->p); /* mark its prototype */
  513. for (i = 0; i < cl->nupvalues; i++) { /* visit its upvalues */
  514. UpVal *uv = cl->upvals[i];
  515. markobjectN(g, uv); /* mark upvalue */
  516. }
  517. return 1 + cl->nupvalues;
  518. }
  519. /*
  520. ** Traverse a thread, marking the elements in the stack up to its top
  521. ** and cleaning the rest of the stack in the final traversal. That
  522. ** ensures that the entire stack have valid (non-dead) objects.
  523. ** Threads have no barriers. In gen. mode, old threads must be visited
  524. ** at every cycle, because they might point to young objects. In inc.
  525. ** mode, the thread can still be modified before the end of the cycle,
  526. ** and therefore it must be visited again in the atomic phase. To ensure
  527. ** these visits, threads must return to a gray list if they are not new
  528. ** (which can only happen in generational mode) or if the traverse is in
  529. ** the propagate phase (which can only happen in incremental mode).
  530. */
  531. static int traversethread (global_State *g, lua_State *th) {
  532. UpVal *uv;
  533. StkId o = th->stack.p;
  534. if (isold(th) || g->gcstate == GCSpropagate)
  535. linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
  536. if (o == NULL)
  537. return 1; /* stack not completely built yet */
  538. lua_assert(g->gcstate == GCSatomic ||
  539. th->openupval == NULL || isintwups(th));
  540. for (; o < th->top.p; o++) /* mark live elements in the stack */
  541. markvalue(g, s2v(o));
  542. for (uv = th->openupval; uv != NULL; uv = uv->u.open.next)
  543. markobject(g, uv); /* open upvalues cannot be collected */
  544. if (g->gcstate == GCSatomic) { /* final traversal? */
  545. if (!g->gcemergency)
  546. luaD_shrinkstack(th); /* do not change stack in emergency cycle */
  547. for (o = th->top.p; o < th->stack_last.p + EXTRA_STACK; o++)
  548. setnilvalue(s2v(o)); /* clear dead stack slice */
  549. /* 'remarkupvals' may have removed thread from 'twups' list */
  550. if (!isintwups(th) && th->openupval != NULL) {
  551. th->twups = g->twups; /* link it back to the list */
  552. g->twups = th;
  553. }
  554. }
  555. return 1 + stacksize(th);
  556. }
  557. /*
  558. ** traverse one gray object, turning it to black.
  559. */
  560. static lu_mem propagatemark (global_State *g) {
  561. GCObject *o = g->gray;
  562. nw2black(o);
  563. g->gray = *getgclist(o); /* remove from 'gray' list */
  564. switch (o->tt) {
  565. case LUA_VTABLE: return traversetable(g, gco2t(o));
  566. case LUA_VUSERDATA: return traverseudata(g, gco2u(o));
  567. case LUA_VLCL: return traverseLclosure(g, gco2lcl(o));
  568. case LUA_VCCL: return traverseCclosure(g, gco2ccl(o));
  569. case LUA_VPROTO: return traverseproto(g, gco2p(o));
  570. case LUA_VTHREAD: return traversethread(g, gco2th(o));
  571. default: lua_assert(0); return 0;
  572. }
  573. }
  574. static lu_mem propagateall (global_State *g) {
  575. lu_mem tot = 0;
  576. while (g->gray)
  577. tot += propagatemark(g);
  578. return tot;
  579. }
  580. /*
  581. ** Traverse all ephemeron tables propagating marks from keys to values.
  582. ** Repeat until it converges, that is, nothing new is marked. 'dir'
  583. ** inverts the direction of the traversals, trying to speed up
  584. ** convergence on chains in the same table.
  585. **
  586. */
  587. static void convergeephemerons (global_State *g) {
  588. int changed;
  589. int dir = 0;
  590. do {
  591. GCObject *w;
  592. GCObject *next = g->ephemeron; /* get ephemeron list */
  593. g->ephemeron = NULL; /* tables may return to this list when traversed */
  594. changed = 0;
  595. while ((w = next) != NULL) { /* for each ephemeron table */
  596. Table *h = gco2t(w);
  597. next = h->gclist; /* list is rebuilt during loop */
  598. nw2black(h); /* out of the list (for now) */
  599. if (traverseephemeron(g, h, dir)) { /* marked some value? */
  600. propagateall(g); /* propagate changes */
  601. changed = 1; /* will have to revisit all ephemeron tables */
  602. }
  603. }
  604. dir = !dir; /* invert direction next time */
  605. } while (changed); /* repeat until no more changes */
  606. }
  607. /* }====================================================== */
  608. /*
  609. ** {======================================================
  610. ** Sweep Functions
  611. ** =======================================================
  612. */
  613. /*
  614. ** clear entries with unmarked keys from all weaktables in list 'l'
  615. */
  616. static void clearbykeys (global_State *g, GCObject *l) {
  617. for (; l; l = gco2t(l)->gclist) {
  618. Table *h = gco2t(l);
  619. Node *limit = gnodelast(h);
  620. Node *n;
  621. for (n = gnode(h, 0); n < limit; n++) {
  622. if (iscleared(g, gckeyN(n))) /* unmarked key? */
  623. setempty(gval(n)); /* remove entry */
  624. if (isempty(gval(n))) /* is entry empty? */
  625. clearkey(n); /* clear its key */
  626. }
  627. }
  628. }
  629. /*
  630. ** clear entries with unmarked values from all weaktables in list 'l' up
  631. ** to element 'f'
  632. */
  633. static void clearbyvalues (global_State *g, GCObject *l, GCObject *f) {
  634. for (; l != f; l = gco2t(l)->gclist) {
  635. Table *h = gco2t(l);
  636. Node *n, *limit = gnodelast(h);
  637. unsigned int i;
  638. unsigned int asize = luaH_realasize(h);
  639. for (i = 0; i < asize; i++) {
  640. TValue *o = &h->array[i];
  641. if (iscleared(g, gcvalueN(o))) /* value was collected? */
  642. setempty(o); /* remove entry */
  643. }
  644. for (n = gnode(h, 0); n < limit; n++) {
  645. if (iscleared(g, gcvalueN(gval(n)))) /* unmarked value? */
  646. setempty(gval(n)); /* remove entry */
  647. if (isempty(gval(n))) /* is entry empty? */
  648. clearkey(n); /* clear its key */
  649. }
  650. }
  651. }
  652. static void freeupval (lua_State *L, UpVal *uv) {
  653. if (upisopen(uv))
  654. luaF_unlinkupval(uv);
  655. luaM_free(L, uv);
  656. }
  657. static void freeobj (lua_State *L, GCObject *o) {
  658. switch (o->tt) {
  659. case LUA_VPROTO:
  660. luaF_freeproto(L, gco2p(o));
  661. break;
  662. case LUA_VUPVAL:
  663. freeupval(L, gco2upv(o));
  664. break;
  665. case LUA_VLCL: {
  666. LClosure *cl = gco2lcl(o);
  667. luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
  668. break;
  669. }
  670. case LUA_VCCL: {
  671. CClosure *cl = gco2ccl(o);
  672. luaM_freemem(L, cl, sizeCclosure(cl->nupvalues));
  673. break;
  674. }
  675. case LUA_VTABLE:
  676. luaH_free(L, gco2t(o));
  677. break;
  678. case LUA_VTHREAD:
  679. luaE_freethread(L, gco2th(o));
  680. break;
  681. case LUA_VUSERDATA: {
  682. Udata *u = gco2u(o);
  683. luaM_freemem(L, o, sizeudata(u->nuvalue, u->len));
  684. break;
  685. }
  686. case LUA_VSHRSTR: {
  687. TString *ts = gco2ts(o);
  688. luaS_remove(L, ts); /* remove it from hash table */
  689. luaM_freemem(L, ts, sizelstring(ts->shrlen));
  690. break;
  691. }
  692. case LUA_VLNGSTR: {
  693. TString *ts = gco2ts(o);
  694. luaM_freemem(L, ts, sizelstring(ts->u.lnglen));
  695. break;
  696. }
  697. default: lua_assert(0);
  698. }
  699. }
  700. /*
  701. ** sweep at most 'countin' elements from a list of GCObjects erasing dead
  702. ** objects, where a dead object is one marked with the old (non current)
  703. ** white; change all non-dead objects back to white, preparing for next
  704. ** collection cycle. Return where to continue the traversal or NULL if
  705. ** list is finished. ('*countout' gets the number of elements traversed.)
  706. */
  707. static GCObject **sweeplist (lua_State *L, GCObject **p, int countin,
  708. int *countout) {
  709. global_State *g = G(L);
  710. int ow = otherwhite(g);
  711. int i;
  712. int white = luaC_white(g); /* current white */
  713. for (i = 0; *p != NULL && i < countin; i++) {
  714. GCObject *curr = *p;
  715. int marked = curr->marked;
  716. 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 (iswhite(curr)) { /* is 'curr' dead? */
  934. lua_assert(isdead(g, curr));
  935. *p = curr->next; /* remove 'curr' from list */
  936. freeobj(L, curr); /* erase 'curr' */
  937. }
  938. else { /* all surviving objects become old */
  939. setage(curr, G_OLD);
  940. if (curr->tt == LUA_VTHREAD) { /* threads must be watched */
  941. lua_State *th = gco2th(curr);
  942. linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
  943. }
  944. else if (curr->tt == LUA_VUPVAL && upisopen(gco2upv(curr)))
  945. set2gray(curr); /* open upvalues are always gray */
  946. else /* everything else is black */
  947. nw2black(curr);
  948. p = &curr->next; /* go to next element */
  949. }
  950. }
  951. }
  952. /*
  953. ** Sweep for generational mode. Delete dead objects. (Because the
  954. ** collection is not incremental, there are no "new white" objects
  955. ** during the sweep. So, any white object must be dead.) For
  956. ** non-dead objects, advance their ages and clear the color of
  957. ** new objects. (Old objects keep their colors.)
  958. ** The ages of G_TOUCHED1 and G_TOUCHED2 objects cannot be advanced
  959. ** here, because these old-generation objects are usually not swept
  960. ** here. They will all be advanced in 'correctgraylist'. That function
  961. ** will also remove objects turned white here from any gray list.
  962. */
  963. static GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p,
  964. GCObject *limit, GCObject **pfirstold1) {
  965. static const lu_byte nextage[] = {
  966. G_SURVIVAL, /* from G_NEW */
  967. G_OLD1, /* from G_SURVIVAL */
  968. G_OLD1, /* from G_OLD0 */
  969. G_OLD, /* from G_OLD1 */
  970. G_OLD, /* from G_OLD (do not change) */
  971. G_TOUCHED1, /* from G_TOUCHED1 (do not change) */
  972. G_TOUCHED2 /* from G_TOUCHED2 (do not change) */
  973. };
  974. int white = luaC_white(g);
  975. GCObject *curr;
  976. while ((curr = *p) != limit) {
  977. if (iswhite(curr)) { /* is 'curr' dead? */
  978. lua_assert(!isold(curr) && isdead(g, curr));
  979. *p = curr->next; /* remove 'curr' from list */
  980. freeobj(L, curr); /* erase 'curr' */
  981. }
  982. else { /* correct mark and age */
  983. if (getage(curr) == G_NEW) { /* new objects go back to white */
  984. int marked = curr->marked & ~maskgcbits; /* erase GC bits */
  985. curr->marked = cast_byte(marked | G_SURVIVAL | white);
  986. }
  987. else { /* all other objects will be old, and so keep their color */
  988. setage(curr, nextage[getage(curr)]);
  989. if (getage(curr) == G_OLD1 && *pfirstold1 == NULL)
  990. *pfirstold1 = curr; /* first OLD1 object in the list */
  991. }
  992. p = &curr->next; /* go to next element */
  993. }
  994. }
  995. return p;
  996. }
  997. /*
  998. ** Traverse a list making all its elements white and clearing their
  999. ** age. In incremental mode, all objects are 'new' all the time,
  1000. ** except for fixed strings (which are always old).
  1001. */
  1002. static void whitelist (global_State *g, GCObject *p) {
  1003. int white = luaC_white(g);
  1004. for (; p != NULL; p = p->next)
  1005. p->marked = cast_byte((p->marked & ~maskgcbits) | white);
  1006. }
  1007. /*
  1008. ** Correct a list of gray objects. Return pointer to where rest of the
  1009. ** list should be linked.
  1010. ** Because this correction is done after sweeping, young objects might
  1011. ** be turned white and still be in the list. They are only removed.
  1012. ** 'TOUCHED1' objects are advanced to 'TOUCHED2' and remain on the list;
  1013. ** Non-white threads also remain on the list; 'TOUCHED2' objects become
  1014. ** regular old; they and anything else are removed from the list.
  1015. */
  1016. static GCObject **correctgraylist (GCObject **p) {
  1017. GCObject *curr;
  1018. while ((curr = *p) != NULL) {
  1019. GCObject **next = getgclist(curr);
  1020. if (iswhite(curr))
  1021. goto remove; /* remove all white objects */
  1022. else if (getage(curr) == G_TOUCHED1) { /* touched in this cycle? */
  1023. lua_assert(isgray(curr));
  1024. nw2black(curr); /* make it black, for next barrier */
  1025. changeage(curr, G_TOUCHED1, G_TOUCHED2);
  1026. goto remain; /* keep it in the list and go to next element */
  1027. }
  1028. else if (curr->tt == LUA_VTHREAD) {
  1029. lua_assert(isgray(curr));
  1030. goto remain; /* keep non-white threads on the list */
  1031. }
  1032. else { /* everything else is removed */
  1033. lua_assert(isold(curr)); /* young objects should be white here */
  1034. if (getage(curr) == G_TOUCHED2) /* advance from TOUCHED2... */
  1035. changeage(curr, G_TOUCHED2, G_OLD); /* ... to OLD */
  1036. nw2black(curr); /* make object black (to be removed) */
  1037. goto remove;
  1038. }
  1039. remove: *p = *next; continue;
  1040. remain: p = next; continue;
  1041. }
  1042. return p;
  1043. }
  1044. /*
  1045. ** Correct all gray lists, coalescing them into 'grayagain'.
  1046. */
  1047. static void correctgraylists (global_State *g) {
  1048. GCObject **list = correctgraylist(&g->grayagain);
  1049. *list = g->weak; g->weak = NULL;
  1050. list = correctgraylist(list);
  1051. *list = g->allweak; g->allweak = NULL;
  1052. list = correctgraylist(list);
  1053. *list = g->ephemeron; g->ephemeron = NULL;
  1054. correctgraylist(list);
  1055. }
  1056. /*
  1057. ** Mark black 'OLD1' objects when starting a new young collection.
  1058. ** Gray objects are already in some gray list, and so will be visited
  1059. ** in the atomic step.
  1060. */
  1061. static void markold (global_State *g, GCObject *from, GCObject *to) {
  1062. GCObject *p;
  1063. for (p = from; p != to; p = p->next) {
  1064. if (getage(p) == G_OLD1) {
  1065. lua_assert(!iswhite(p));
  1066. changeage(p, G_OLD1, G_OLD); /* now they are old */
  1067. if (isblack(p))
  1068. reallymarkobject(g, p);
  1069. }
  1070. }
  1071. }
  1072. /*
  1073. ** Finish a young-generation collection.
  1074. */
  1075. static void finishgencycle (lua_State *L, global_State *g) {
  1076. correctgraylists(g);
  1077. checkSizes(L, g);
  1078. g->gcstate = GCSpropagate; /* skip restart */
  1079. if (!g->gcemergency)
  1080. callallpendingfinalizers(L);
  1081. }
  1082. /*
  1083. ** Does a young collection. First, mark 'OLD1' objects. Then does the
  1084. ** atomic step. Then, sweep all lists and advance pointers. Finally,
  1085. ** finish the collection.
  1086. */
  1087. static void youngcollection (lua_State *L, global_State *g) {
  1088. GCObject **psurvival; /* to point to first non-dead survival object */
  1089. GCObject *dummy; /* dummy out parameter to 'sweepgen' */
  1090. lua_assert(g->gcstate == GCSpropagate);
  1091. if (g->firstold1) { /* are there regular OLD1 objects? */
  1092. markold(g, g->firstold1, g->reallyold); /* mark them */
  1093. g->firstold1 = NULL; /* no more OLD1 objects (for now) */
  1094. }
  1095. markold(g, g->finobj, g->finobjrold);
  1096. markold(g, g->tobefnz, NULL);
  1097. atomic(L);
  1098. /* sweep nursery and get a pointer to its last live element */
  1099. g->gcstate = GCSswpallgc;
  1100. psurvival = sweepgen(L, g, &g->allgc, g->survival, &g->firstold1);
  1101. /* sweep 'survival' */
  1102. sweepgen(L, g, psurvival, g->old1, &g->firstold1);
  1103. g->reallyold = g->old1;
  1104. g->old1 = *psurvival; /* 'survival' survivals are old now */
  1105. g->survival = g->allgc; /* all news are survivals */
  1106. /* repeat for 'finobj' lists */
  1107. dummy = NULL; /* no 'firstold1' optimization for 'finobj' lists */
  1108. psurvival = sweepgen(L, g, &g->finobj, g->finobjsur, &dummy);
  1109. /* sweep 'survival' */
  1110. sweepgen(L, g, psurvival, g->finobjold1, &dummy);
  1111. g->finobjrold = g->finobjold1;
  1112. g->finobjold1 = *psurvival; /* 'survival' survivals are old now */
  1113. g->finobjsur = g->finobj; /* all news are survivals */
  1114. sweepgen(L, g, &g->tobefnz, NULL, &dummy);
  1115. finishgencycle(L, g);
  1116. }
  1117. /*
  1118. ** Clears all gray lists, sweeps objects, and prepare sublists to enter
  1119. ** generational mode. The sweeps remove dead objects and turn all
  1120. ** surviving objects to old. Threads go back to 'grayagain'; everything
  1121. ** else is turned black (not in any gray list).
  1122. */
  1123. static void atomic2gen (lua_State *L, global_State *g) {
  1124. cleargraylists(g);
  1125. /* sweep all elements making them old */
  1126. g->gcstate = GCSswpallgc;
  1127. sweep2old(L, &g->allgc);
  1128. /* everything alive now is old */
  1129. g->reallyold = g->old1 = g->survival = g->allgc;
  1130. g->firstold1 = NULL; /* there are no OLD1 objects anywhere */
  1131. /* repeat for 'finobj' lists */
  1132. sweep2old(L, &g->finobj);
  1133. g->finobjrold = g->finobjold1 = g->finobjsur = g->finobj;
  1134. sweep2old(L, &g->tobefnz);
  1135. g->gckind = KGC_GEN;
  1136. g->lastatomic = 0;
  1137. g->GCestimate = gettotalbytes(g); /* base for memory control */
  1138. finishgencycle(L, g);
  1139. }
  1140. /*
  1141. ** Set debt for the next minor collection, which will happen when
  1142. ** memory grows 'genminormul'%.
  1143. */
  1144. static void setminordebt (global_State *g) {
  1145. luaE_setdebt(g, -(cast(l_mem, (gettotalbytes(g) / 100)) * g->genminormul));
  1146. }
  1147. /*
  1148. ** Enter generational mode. Must go until the end of an atomic cycle
  1149. ** to ensure that all objects are correctly marked and weak tables
  1150. ** are cleared. Then, turn all objects into old and finishes the
  1151. ** collection.
  1152. */
  1153. static lu_mem entergen (lua_State *L, global_State *g) {
  1154. lu_mem numobjs;
  1155. luaC_runtilstate(L, bitmask(GCSpause)); /* prepare to start a new cycle */
  1156. luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */
  1157. numobjs = atomic(L); /* propagates all and then do the atomic stuff */
  1158. atomic2gen(L, g);
  1159. setminordebt(g); /* set debt assuming next cycle will be minor */
  1160. return numobjs;
  1161. }
  1162. /*
  1163. ** Enter incremental mode. Turn all objects white, make all
  1164. ** intermediate lists point to NULL (to avoid invalid pointers),
  1165. ** and go to the pause state.
  1166. */
  1167. static void enterinc (global_State *g) {
  1168. whitelist(g, g->allgc);
  1169. g->reallyold = g->old1 = g->survival = NULL;
  1170. whitelist(g, g->finobj);
  1171. whitelist(g, g->tobefnz);
  1172. g->finobjrold = g->finobjold1 = g->finobjsur = NULL;
  1173. g->gcstate = GCSpause;
  1174. g->gckind = KGC_INC;
  1175. g->lastatomic = 0;
  1176. }
  1177. /*
  1178. ** Change collector mode to 'newmode'.
  1179. */
  1180. void luaC_changemode (lua_State *L, int newmode) {
  1181. global_State *g = G(L);
  1182. if (newmode != g->gckind) {
  1183. if (newmode == KGC_GEN) /* entering generational mode? */
  1184. entergen(L, g);
  1185. else
  1186. enterinc(g); /* entering incremental mode */
  1187. }
  1188. g->lastatomic = 0;
  1189. }
  1190. /*
  1191. ** Does a full collection in generational mode.
  1192. */
  1193. static lu_mem fullgen (lua_State *L, global_State *g) {
  1194. enterinc(g);
  1195. return entergen(L, g);
  1196. }
  1197. /*
  1198. ** Does a major collection after last collection was a "bad collection".
  1199. **
  1200. ** When the program is building a big structure, it allocates lots of
  1201. ** memory but generates very little garbage. In those scenarios,
  1202. ** the generational mode just wastes time doing small collections, and
  1203. ** major collections are frequently what we call a "bad collection", a
  1204. ** collection that frees too few objects. To avoid the cost of switching
  1205. ** between generational mode and the incremental mode needed for full
  1206. ** (major) collections, the collector tries to stay in incremental mode
  1207. ** after a bad collection, and to switch back to generational mode only
  1208. ** after a "good" collection (one that traverses less than 9/8 objects
  1209. ** of the previous one).
  1210. ** The collector must choose whether to stay in incremental mode or to
  1211. ** switch back to generational mode before sweeping. At this point, it
  1212. ** does not know the real memory in use, so it cannot use memory to
  1213. ** decide whether to return to generational mode. Instead, it uses the
  1214. ** number of objects traversed (returned by 'atomic') as a proxy. The
  1215. ** field 'g->lastatomic' keeps this count from the last collection.
  1216. ** ('g->lastatomic != 0' also means that the last collection was bad.)
  1217. */
  1218. static void stepgenfull (lua_State *L, global_State *g) {
  1219. lu_mem newatomic; /* count of traversed objects */
  1220. lu_mem lastatomic = g->lastatomic; /* count from last collection */
  1221. if (g->gckind == KGC_GEN) /* still in generational mode? */
  1222. enterinc(g); /* enter incremental mode */
  1223. luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */
  1224. newatomic = atomic(L); /* mark everybody */
  1225. if (newatomic < lastatomic + (lastatomic >> 3)) { /* good collection? */
  1226. atomic2gen(L, g); /* return to generational mode */
  1227. setminordebt(g);
  1228. }
  1229. else { /* another bad collection; stay in incremental mode */
  1230. g->GCestimate = gettotalbytes(g); /* first estimate */
  1231. entersweep(L);
  1232. luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */
  1233. setpause(g);
  1234. g->lastatomic = newatomic;
  1235. }
  1236. }
  1237. /*
  1238. ** Does a generational "step".
  1239. ** Usually, this means doing a minor collection and setting the debt to
  1240. ** make another collection when memory grows 'genminormul'% larger.
  1241. **
  1242. ** However, there are exceptions. If memory grows 'genmajormul'%
  1243. ** larger than it was at the end of the last major collection (kept
  1244. ** in 'g->GCestimate'), the function does a major collection. At the
  1245. ** end, it checks whether the major collection was able to free a
  1246. ** decent amount of memory (at least half the growth in memory since
  1247. ** previous major collection). If so, the collector keeps its state,
  1248. ** and the next collection will probably be minor again. Otherwise,
  1249. ** we have what we call a "bad collection". In that case, set the field
  1250. ** 'g->lastatomic' to signal that fact, so that the next collection will
  1251. ** go to 'stepgenfull'.
  1252. **
  1253. ** 'GCdebt <= 0' means an explicit call to GC step with "size" zero;
  1254. ** in that case, do a minor collection.
  1255. */
  1256. static void genstep (lua_State *L, global_State *g) {
  1257. if (g->lastatomic != 0) /* last collection was a bad one? */
  1258. stepgenfull(L, g); /* do a full step */
  1259. else {
  1260. lu_mem majorbase = g->GCestimate; /* memory after last major collection */
  1261. lu_mem majorinc = (majorbase / 100) * getgcparam(g->genmajormul);
  1262. if (g->GCdebt > 0 && gettotalbytes(g) > majorbase + majorinc) {
  1263. lu_mem numobjs = fullgen(L, g); /* do a major collection */
  1264. if (gettotalbytes(g) < majorbase + (majorinc / 2)) {
  1265. /* collected at least half of memory growth since last major
  1266. collection; keep doing minor collections. */
  1267. lua_assert(g->lastatomic == 0);
  1268. }
  1269. else { /* bad collection */
  1270. g->lastatomic = numobjs; /* signal that last collection was bad */
  1271. setpause(g); /* do a long wait for next (major) collection */
  1272. }
  1273. }
  1274. else { /* regular case; do a minor collection */
  1275. youngcollection(L, g);
  1276. setminordebt(g);
  1277. g->GCestimate = majorbase; /* preserve base value */
  1278. }
  1279. }
  1280. lua_assert(isdecGCmodegen(g));
  1281. }
  1282. /* }====================================================== */
  1283. /*
  1284. ** {======================================================
  1285. ** GC control
  1286. ** =======================================================
  1287. */
  1288. /*
  1289. ** Enter first sweep phase.
  1290. ** The call to 'sweeptolive' makes the pointer point to an object
  1291. ** inside the list (instead of to the header), so that the real sweep do
  1292. ** not need to skip objects created between "now" and the start of the
  1293. ** real sweep.
  1294. */
  1295. static void entersweep (lua_State *L) {
  1296. global_State *g = G(L);
  1297. g->gcstate = GCSswpallgc;
  1298. lua_assert(g->sweepgc == NULL);
  1299. g->sweepgc = sweeptolive(L, &g->allgc);
  1300. }
  1301. /*
  1302. ** Delete all objects in list 'p' until (but not including) object
  1303. ** 'limit'.
  1304. */
  1305. static void deletelist (lua_State *L, GCObject *p, GCObject *limit) {
  1306. while (p != limit) {
  1307. GCObject *next = p->next;
  1308. freeobj(L, p);
  1309. p = next;
  1310. }
  1311. }
  1312. /*
  1313. ** Call all finalizers of the objects in the given Lua state, and
  1314. ** then free all objects, except for the main thread.
  1315. */
  1316. void luaC_freeallobjects (lua_State *L) {
  1317. global_State *g = G(L);
  1318. g->gcstp = GCSTPCLS; /* no extra finalizers after here */
  1319. luaC_changemode(L, KGC_INC);
  1320. separatetobefnz(g, 1); /* separate all objects with finalizers */
  1321. lua_assert(g->finobj == NULL);
  1322. callallpendingfinalizers(L);
  1323. deletelist(L, g->allgc, obj2gco(g->mainthread));
  1324. lua_assert(g->finobj == NULL); /* no new finalizers */
  1325. deletelist(L, g->fixedgc, NULL); /* collect fixed objects */
  1326. lua_assert(g->strt.nuse == 0);
  1327. }
  1328. static lu_mem atomic (lua_State *L) {
  1329. global_State *g = G(L);
  1330. lu_mem work = 0;
  1331. GCObject *origweak, *origall;
  1332. GCObject *grayagain = g->grayagain; /* save original list */
  1333. g->grayagain = NULL;
  1334. lua_assert(g->ephemeron == NULL && g->weak == NULL);
  1335. lua_assert(!iswhite(g->mainthread));
  1336. g->gcstate = GCSatomic;
  1337. markobject(g, L); /* mark running thread */
  1338. /* registry and global metatables may be changed by API */
  1339. markvalue(g, &g->l_registry);
  1340. markmt(g); /* mark global metatables */
  1341. work += propagateall(g); /* empties 'gray' list */
  1342. /* remark occasional upvalues of (maybe) dead threads */
  1343. work += remarkupvals(g);
  1344. work += propagateall(g); /* propagate changes */
  1345. g->gray = grayagain;
  1346. work += propagateall(g); /* traverse 'grayagain' list */
  1347. convergeephemerons(g);
  1348. /* at this point, all strongly accessible objects are marked. */
  1349. /* Clear values from weak tables, before checking finalizers */
  1350. clearbyvalues(g, g->weak, NULL);
  1351. clearbyvalues(g, g->allweak, NULL);
  1352. origweak = g->weak; origall = g->allweak;
  1353. separatetobefnz(g, 0); /* separate objects to be finalized */
  1354. work += markbeingfnz(g); /* mark objects that will be finalized */
  1355. work += propagateall(g); /* remark, to propagate 'resurrection' */
  1356. convergeephemerons(g);
  1357. /* at this point, all resurrected objects are marked. */
  1358. /* remove dead objects from weak tables */
  1359. clearbykeys(g, g->ephemeron); /* clear keys from all ephemeron tables */
  1360. clearbykeys(g, g->allweak); /* clear keys from all 'allweak' tables */
  1361. /* clear values from resurrected weak tables */
  1362. clearbyvalues(g, g->weak, origweak);
  1363. clearbyvalues(g, g->allweak, origall);
  1364. luaS_clearcache(g);
  1365. g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
  1366. lua_assert(g->gray == NULL);
  1367. return work; /* estimate of slots marked by 'atomic' */
  1368. }
  1369. static int sweepstep (lua_State *L, global_State *g,
  1370. int nextstate, GCObject **nextlist) {
  1371. if (g->sweepgc) {
  1372. l_mem olddebt = g->GCdebt;
  1373. int count;
  1374. g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX, &count);
  1375. g->GCestimate += g->GCdebt - olddebt; /* update estimate */
  1376. return count;
  1377. }
  1378. else { /* enter next state */
  1379. g->gcstate = nextstate;
  1380. g->sweepgc = nextlist;
  1381. return 0; /* no work done */
  1382. }
  1383. }
  1384. static lu_mem singlestep (lua_State *L) {
  1385. global_State *g = G(L);
  1386. lu_mem work;
  1387. lua_assert(!g->gcstopem); /* collector is not reentrant */
  1388. g->gcstopem = 1; /* no emergency collections while collecting */
  1389. switch (g->gcstate) {
  1390. case GCSpause: {
  1391. restartcollection(g);
  1392. g->gcstate = GCSpropagate;
  1393. work = 1;
  1394. break;
  1395. }
  1396. case GCSpropagate: {
  1397. if (g->gray == NULL) { /* no more gray objects? */
  1398. g->gcstate = GCSenteratomic; /* finish propagate phase */
  1399. work = 0;
  1400. }
  1401. else
  1402. work = propagatemark(g); /* traverse one gray object */
  1403. break;
  1404. }
  1405. case GCSenteratomic: {
  1406. work = atomic(L); /* work is what was traversed by 'atomic' */
  1407. entersweep(L);
  1408. g->GCestimate = gettotalbytes(g); /* first estimate */
  1409. break;
  1410. }
  1411. case GCSswpallgc: { /* sweep "regular" objects */
  1412. work = sweepstep(L, g, GCSswpfinobj, &g->finobj);
  1413. break;
  1414. }
  1415. case GCSswpfinobj: { /* sweep objects with finalizers */
  1416. work = sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
  1417. break;
  1418. }
  1419. case GCSswptobefnz: { /* sweep objects to be finalized */
  1420. work = sweepstep(L, g, GCSswpend, NULL);
  1421. break;
  1422. }
  1423. case GCSswpend: { /* finish sweeps */
  1424. checkSizes(L, g);
  1425. g->gcstate = GCScallfin;
  1426. work = 0;
  1427. break;
  1428. }
  1429. case GCScallfin: { /* call remaining finalizers */
  1430. if (g->tobefnz && !g->gcemergency) {
  1431. g->gcstopem = 0; /* ok collections during finalizers */
  1432. work = runafewfinalizers(L, GCFINMAX) * GCFINALIZECOST;
  1433. }
  1434. else { /* emergency mode or no more finalizers */
  1435. g->gcstate = GCSpause; /* finish collection */
  1436. work = 0;
  1437. }
  1438. break;
  1439. }
  1440. default: lua_assert(0); return 0;
  1441. }
  1442. g->gcstopem = 0;
  1443. return work;
  1444. }
  1445. /*
  1446. ** advances the garbage collector until it reaches a state allowed
  1447. ** by 'statemask'
  1448. */
  1449. void luaC_runtilstate (lua_State *L, int statesmask) {
  1450. global_State *g = G(L);
  1451. while (!testbit(statesmask, g->gcstate))
  1452. singlestep(L);
  1453. }
  1454. /*
  1455. ** Performs a basic incremental step. The debt and step size are
  1456. ** converted from bytes to "units of work"; then the function loops
  1457. ** running single steps until adding that many units of work or
  1458. ** finishing a cycle (pause state). Finally, it sets the debt that
  1459. ** controls when next step will be performed.
  1460. */
  1461. static void incstep (lua_State *L, global_State *g) {
  1462. int stepmul = (getgcparam(g->gcstepmul) | 1); /* avoid division by 0 */
  1463. l_mem debt = (g->GCdebt / WORK2MEM) * stepmul;
  1464. l_mem stepsize = (g->gcstepsize <= log2maxs(l_mem))
  1465. ? ((cast(l_mem, 1) << g->gcstepsize) / WORK2MEM) * stepmul
  1466. : MAX_LMEM; /* overflow; keep maximum value */
  1467. do { /* repeat until pause or enough "credit" (negative debt) */
  1468. lu_mem work = singlestep(L); /* perform one single step */
  1469. debt -= work;
  1470. } while (debt > -stepsize && g->gcstate != GCSpause);
  1471. if (g->gcstate == GCSpause)
  1472. setpause(g); /* pause until next cycle */
  1473. else {
  1474. debt = (debt / stepmul) * WORK2MEM; /* convert 'work units' to bytes */
  1475. luaE_setdebt(g, debt);
  1476. }
  1477. }
  1478. /*
  1479. ** Performs a basic GC step if collector is running. (If collector is
  1480. ** not running, set a reasonable debt to avoid it being called at
  1481. ** every single check.)
  1482. */
  1483. void luaC_step (lua_State *L) {
  1484. global_State *g = G(L);
  1485. if (!gcrunning(g)) /* not running? */
  1486. luaE_setdebt(g, -2000);
  1487. else {
  1488. if(isdecGCmodegen(g))
  1489. genstep(L, g);
  1490. else
  1491. incstep(L, g);
  1492. }
  1493. }
  1494. /*
  1495. ** Perform a full collection in incremental mode.
  1496. ** Before running the collection, check 'keepinvariant'; if it is true,
  1497. ** there may be some objects marked as black, so the collector has
  1498. ** to sweep all objects to turn them back to white (as white has not
  1499. ** changed, nothing will be collected).
  1500. */
  1501. static void fullinc (lua_State *L, global_State *g) {
  1502. if (keepinvariant(g)) /* black objects? */
  1503. entersweep(L); /* sweep everything to turn them back to white */
  1504. /* finish any pending sweep phase to start a new cycle */
  1505. luaC_runtilstate(L, bitmask(GCSpause));
  1506. luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */
  1507. g->gcstate = GCSenteratomic; /* go straight to atomic phase */
  1508. luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */
  1509. /* estimate must be correct after a full GC cycle */
  1510. lua_assert(g->GCestimate == gettotalbytes(g));
  1511. luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */
  1512. setpause(g);
  1513. }
  1514. /*
  1515. ** Performs a full GC cycle; if 'isemergency', set a flag to avoid
  1516. ** some operations which could change the interpreter state in some
  1517. ** unexpected ways (running finalizers and shrinking some structures).
  1518. */
  1519. void luaC_fullgc (lua_State *L, int isemergency) {
  1520. global_State *g = G(L);
  1521. lua_assert(!g->gcemergency);
  1522. g->gcemergency = isemergency; /* set flag */
  1523. if (g->gckind == KGC_INC)
  1524. fullinc(L, g);
  1525. else
  1526. fullgen(L, g);
  1527. g->gcemergency = 0;
  1528. }
  1529. /* }====================================================== */