lstate.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. /*
  2. ** $Id: lstate.h $
  3. ** Global State
  4. ** See Copyright Notice in lua.h
  5. */
  6. #ifndef lstate_h
  7. #define lstate_h
  8. #include "lua.h"
  9. #include "lobject.h"
  10. #include "ltm.h"
  11. #include "lzio.h"
  12. /*
  13. ** Some notes about garbage-collected objects: All objects in Lua must
  14. ** be kept somehow accessible until being freed, so all objects always
  15. ** belong to one (and only one) of these lists, using field 'next' of
  16. ** the 'CommonHeader' for the link:
  17. **
  18. ** 'allgc': all objects not marked for finalization;
  19. ** 'finobj': all objects marked for finalization;
  20. ** 'tobefnz': all objects ready to be finalized;
  21. ** 'fixedgc': all objects that are not to be collected (currently
  22. ** only small strings, such as reserved words).
  23. **
  24. ** For the generational collector, some of these lists have marks for
  25. ** generations. Each mark points to the first element in the list for
  26. ** that particular generation; that generation goes until the next mark.
  27. **
  28. ** 'allgc' -> 'survival': new objects;
  29. ** 'survival' -> 'old': objects that survived one collection;
  30. ** 'old1' -> 'reallyold': objects that became old in last collection;
  31. ** 'reallyold' -> NULL: objects old for more than one cycle.
  32. **
  33. ** 'finobj' -> 'finobjsur': new objects marked for finalization;
  34. ** 'finobjsur' -> 'finobjold1': survived """";
  35. ** 'finobjold1' -> 'finobjrold': just old """";
  36. ** 'finobjrold' -> NULL: really old """".
  37. **
  38. ** All lists can contain elements older than their main ages, due
  39. ** to 'luaC_checkfinalizer' and 'udata2finalize', which move
  40. ** objects between the normal lists and the "marked for finalization"
  41. ** lists. Moreover, barriers can age young objects in young lists as
  42. ** OLD0, which then become OLD1. However, a list never contains
  43. ** elements younger than their main ages.
  44. **
  45. ** The generational collector also uses a pointer 'firstold1', which
  46. ** points to the first OLD1 object in the list. It is used to optimize
  47. ** 'markold'. (Potentially OLD1 objects can be anywhere between 'allgc'
  48. ** and 'reallyold', but often the list has no OLD1 objects or they are
  49. ** after 'old1'.) Note the difference between it and 'old1':
  50. ** 'firstold1': no OLD1 objects before this point; there can be all
  51. ** ages after it.
  52. ** 'old1': no objects younger than OLD1 after this point.
  53. */
  54. /*
  55. ** Moreover, there is another set of lists that control gray objects.
  56. ** These lists are linked by fields 'gclist'. (All objects that
  57. ** can become gray have such a field. The field is not the same
  58. ** in all objects, but it always has this name.) Any gray object
  59. ** must belong to one of these lists, and all objects in these lists
  60. ** must be gray (with two exceptions explained below):
  61. **
  62. ** 'gray': regular gray objects, still waiting to be visited.
  63. ** 'grayagain': objects that must be revisited at the atomic phase.
  64. ** That includes
  65. ** - black objects got in a write barrier;
  66. ** - all kinds of weak tables during propagation phase;
  67. ** - all threads.
  68. ** 'weak': tables with weak values to be cleared;
  69. ** 'ephemeron': ephemeron tables with white->white entries;
  70. ** 'allweak': tables with weak keys and/or weak values to be cleared.
  71. **
  72. ** The exceptions to that "gray rule" are:
  73. ** - TOUCHED2 objects in generational mode stay in a gray list (because
  74. ** they must be visited again at the end of the cycle), but they are
  75. ** marked black because assignments to them must activate barriers (to
  76. ** move them back to TOUCHED1).
  77. ** - Open upvales are kept gray to avoid barriers, but they stay out
  78. ** of gray lists. (They don't even have a 'gclist' field.)
  79. */
  80. /*
  81. ** About 'nCcalls': each thread in Lua (a lua_State) keeps a count of
  82. ** how many "C calls" it still can do in the C stack, to avoid C-stack
  83. ** overflow. This count is very rough approximation; it considers only
  84. ** recursive functions inside the interpreter, as non-recursive calls
  85. ** can be considered using a fixed (although unknown) amount of stack
  86. ** space.
  87. **
  88. ** The count has two parts: the lower part is the count itself; the
  89. ** higher part counts the number of non-yieldable calls in the stack.
  90. ** (They are together so that we can change both with one instruction.)
  91. **
  92. ** Because calls to external C functions can use an unknown amount
  93. ** of space (e.g., functions using an auxiliary buffer), calls
  94. ** to these functions add more than one to the count (see CSTACKCF).
  95. **
  96. ** The proper count excludes the number of CallInfo structures allocated
  97. ** by Lua, as a kind of "potential" calls. So, when Lua calls a function
  98. ** (and "consumes" one CallInfo), it needs neither to decrement nor to
  99. ** check 'nCcalls', as its use of C stack is already accounted for.
  100. */
  101. /* number of "C stack slots" used by an external C function */
  102. #define CSTACKCF 10
  103. /*
  104. ** The C-stack size is sliced in the following zones:
  105. ** - larger than CSTACKERR: normal stack;
  106. ** - [CSTACKMARK, CSTACKERR]: buffer zone to signal a stack overflow;
  107. ** - [CSTACKCF, CSTACKERRMARK]: error-handling zone;
  108. ** - below CSTACKERRMARK: buffer zone to signal overflow during overflow;
  109. ** (Because the counter can be decremented CSTACKCF at once, we need
  110. ** the so called "buffer zones", with at least that size, to properly
  111. ** detect a change from one zone to the next.)
  112. */
  113. #define CSTACKERR (8 * CSTACKCF)
  114. #define CSTACKMARK (CSTACKERR - (CSTACKCF + 2))
  115. #define CSTACKERRMARK (CSTACKCF + 2)
  116. /* initial limit for the C-stack of threads */
  117. #define CSTACKTHREAD (2 * CSTACKERR)
  118. /* true if this thread does not have non-yieldable calls in the stack */
  119. #define yieldable(L) (((L)->nCcalls & 0xffff0000) == 0)
  120. /* real number of C calls */
  121. #define getCcalls(L) ((L)->nCcalls & 0xffff)
  122. /* Increment the number of non-yieldable calls */
  123. #define incnny(L) ((L)->nCcalls += 0x10000)
  124. /* Decrement the number of non-yieldable calls */
  125. #define decnny(L) ((L)->nCcalls -= 0x10000)
  126. /* Increment the number of non-yieldable calls and decrement nCcalls */
  127. #define incXCcalls(L) ((L)->nCcalls += 0x10000 - CSTACKCF)
  128. /* Decrement the number of non-yieldable calls and increment nCcalls */
  129. #define decXCcalls(L) ((L)->nCcalls -= 0x10000 - CSTACKCF)
  130. struct lua_longjmp; /* defined in ldo.c */
  131. /*
  132. ** Atomic type (relative to signals) to better ensure that 'lua_sethook'
  133. ** is thread safe
  134. */
  135. #if !defined(l_signalT)
  136. #include <signal.h>
  137. #define l_signalT sig_atomic_t
  138. #endif
  139. /* extra stack space to handle TM calls and some other extras */
  140. #define EXTRA_STACK 5
  141. #define BASIC_STACK_SIZE (2*LUA_MINSTACK)
  142. /* kinds of Garbage Collection */
  143. #define KGC_INC 0 /* incremental gc */
  144. #define KGC_GEN 1 /* generational gc */
  145. typedef struct stringtable {
  146. TString **hash;
  147. int nuse; /* number of elements */
  148. int size;
  149. } stringtable;
  150. /*
  151. ** Information about a call.
  152. */
  153. typedef struct CallInfo {
  154. StkId func; /* function index in the stack */
  155. StkId top; /* top for this function */
  156. struct CallInfo *previous, *next; /* dynamic call link */
  157. union {
  158. struct { /* only for Lua functions */
  159. const Instruction *savedpc;
  160. volatile l_signalT trap;
  161. int nextraargs; /* # of extra arguments in vararg functions */
  162. } l;
  163. struct { /* only for C functions */
  164. lua_KFunction k; /* continuation in case of yields */
  165. ptrdiff_t old_errfunc;
  166. lua_KContext ctx; /* context info. in case of yields */
  167. } c;
  168. } u;
  169. union {
  170. int funcidx; /* called-function index */
  171. int nyield; /* number of values yielded */
  172. struct { /* info about transferred values (for call/return hooks) */
  173. unsigned short ftransfer; /* offset of first value transferred */
  174. unsigned short ntransfer; /* number of values transferred */
  175. } transferinfo;
  176. } u2;
  177. short nresults; /* expected number of results from this function */
  178. unsigned short callstatus;
  179. } CallInfo;
  180. /*
  181. ** Bits in CallInfo status
  182. */
  183. #define CIST_OAH (1<<0) /* original value of 'allowhook' */
  184. #define CIST_C (1<<1) /* call is running a C function */
  185. #define CIST_HOOKED (1<<2) /* call is running a debug hook */
  186. #define CIST_YPCALL (1<<3) /* call is a yieldable protected call */
  187. #define CIST_TAIL (1<<4) /* call was tail called */
  188. #define CIST_HOOKYIELD (1<<5) /* last hook called yielded */
  189. #define CIST_FIN (1<<6) /* call is running a finalizer */
  190. #define CIST_TRAN (1<<7) /* 'ci' has transfer information */
  191. #if defined(LUA_COMPAT_LT_LE)
  192. #define CIST_LEQ (1<<8) /* using __lt for __le */
  193. #endif
  194. /* active function is a Lua function */
  195. #define isLua(ci) (!((ci)->callstatus & CIST_C))
  196. /* call is running Lua code (not a hook) */
  197. #define isLuacode(ci) (!((ci)->callstatus & (CIST_C | CIST_HOOKED)))
  198. /* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */
  199. #define setoah(st,v) ((st) = ((st) & ~CIST_OAH) | (v))
  200. #define getoah(st) ((st) & CIST_OAH)
  201. /*
  202. ** 'global state', shared by all threads of this state
  203. */
  204. typedef struct global_State {
  205. lua_Alloc frealloc; /* function to reallocate memory */
  206. void *ud; /* auxiliary data to 'frealloc' */
  207. l_mem totalbytes; /* number of bytes currently allocated - GCdebt */
  208. l_mem GCdebt; /* bytes allocated not yet compensated by the collector */
  209. lu_mem GCestimate; /* an estimate of the non-garbage memory in use */
  210. lu_mem lastatomic; /* see function 'genstep' in file 'lgc.c' */
  211. stringtable strt; /* hash table for strings */
  212. TValue l_registry;
  213. TValue nilvalue; /* a nil value */
  214. unsigned int seed; /* randomized seed for hashes */
  215. lu_byte currentwhite;
  216. lu_byte gcstate; /* state of garbage collector */
  217. lu_byte gckind; /* kind of GC running */
  218. lu_byte genminormul; /* control for minor generational collections */
  219. lu_byte genmajormul; /* control for major generational collections */
  220. lu_byte gcrunning; /* true if GC is running */
  221. lu_byte gcemergency; /* true if this is an emergency collection */
  222. lu_byte gcpause; /* size of pause between successive GCs */
  223. lu_byte gcstepmul; /* GC "speed" */
  224. lu_byte gcstepsize; /* (log2 of) GC granularity */
  225. GCObject *allgc; /* list of all collectable objects */
  226. GCObject **sweepgc; /* current position of sweep in list */
  227. GCObject *finobj; /* list of collectable objects with finalizers */
  228. GCObject *gray; /* list of gray objects */
  229. GCObject *grayagain; /* list of objects to be traversed atomically */
  230. GCObject *weak; /* list of tables with weak values */
  231. GCObject *ephemeron; /* list of ephemeron tables (weak keys) */
  232. GCObject *allweak; /* list of all-weak tables */
  233. GCObject *tobefnz; /* list of userdata to be GC */
  234. GCObject *fixedgc; /* list of objects not to be collected */
  235. /* fields for generational collector */
  236. GCObject *survival; /* start of objects that survived one GC cycle */
  237. GCObject *old1; /* start of old1 objects */
  238. GCObject *reallyold; /* objects more than one cycle old ("really old") */
  239. GCObject *firstold1; /* first OLD1 object in the list (if any) */
  240. GCObject *finobjsur; /* list of survival objects with finalizers */
  241. GCObject *finobjold1; /* list of old1 objects with finalizers */
  242. GCObject *finobjrold; /* list of really old objects with finalizers */
  243. struct lua_State *twups; /* list of threads with open upvalues */
  244. lua_CFunction panic; /* to be called in unprotected errors */
  245. struct lua_State *mainthread;
  246. TString *memerrmsg; /* message for memory-allocation errors */
  247. TString *tmname[TM_N]; /* array with tag-method names */
  248. struct Table *mt[LUA_NUMTAGS]; /* metatables for basic types */
  249. TString *strcache[STRCACHE_N][STRCACHE_M]; /* cache for strings in API */
  250. lua_WarnFunction warnf; /* warning function */
  251. void *ud_warn; /* auxiliary data to 'warnf' */
  252. unsigned int Cstacklimit; /* current limit for the C stack */
  253. } global_State;
  254. /*
  255. ** 'per thread' state
  256. */
  257. struct lua_State {
  258. CommonHeader;
  259. lu_byte status;
  260. lu_byte allowhook;
  261. unsigned short nci; /* number of items in 'ci' list */
  262. StkId top; /* first free slot in the stack */
  263. global_State *l_G;
  264. CallInfo *ci; /* call info for current function */
  265. StkId stack_last; /* last free slot in the stack */
  266. StkId stack; /* stack base */
  267. UpVal *openupval; /* list of open upvalues in this stack */
  268. GCObject *gclist;
  269. struct lua_State *twups; /* list of threads with open upvalues */
  270. struct lua_longjmp *errorJmp; /* current error recover point */
  271. CallInfo base_ci; /* CallInfo for first level (C calling Lua) */
  272. volatile lua_Hook hook;
  273. ptrdiff_t errfunc; /* current error handling function (stack index) */
  274. l_uint32 nCcalls; /* number of allowed nested C calls - 'nci' */
  275. int oldpc; /* last pc traced */
  276. int stacksize;
  277. int basehookcount;
  278. int hookcount;
  279. volatile l_signalT hookmask;
  280. };
  281. #define G(L) (L->l_G)
  282. /*
  283. ** Union of all collectable objects (only for conversions)
  284. ** ISO C99, 6.5.2.3 p.5:
  285. ** "if a union contains several structures that share a common initial
  286. ** sequence [...], and if the union object currently contains one
  287. ** of these structures, it is permitted to inspect the common initial
  288. ** part of any of them anywhere that a declaration of the complete type
  289. ** of the union is visible."
  290. */
  291. union GCUnion {
  292. GCObject gc; /* common header */
  293. struct TString ts;
  294. struct Udata u;
  295. union Closure cl;
  296. struct Table h;
  297. struct Proto p;
  298. struct lua_State th; /* thread */
  299. struct UpVal upv;
  300. };
  301. /*
  302. ** ISO C99, 6.7.2.1 p.14:
  303. ** "A pointer to a union object, suitably converted, points to each of
  304. ** its members [...], and vice versa."
  305. */
  306. #define cast_u(o) cast(union GCUnion *, (o))
  307. /* macros to convert a GCObject into a specific value */
  308. #define gco2ts(o) \
  309. check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))
  310. #define gco2u(o) check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u))
  311. #define gco2lcl(o) check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l))
  312. #define gco2ccl(o) check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c))
  313. #define gco2cl(o) \
  314. check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))
  315. #define gco2t(o) check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h))
  316. #define gco2p(o) check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p))
  317. #define gco2th(o) check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th))
  318. #define gco2upv(o) check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv))
  319. /*
  320. ** macro to convert a Lua object into a GCObject
  321. ** (The access to 'tt' tries to ensure that 'v' is actually a Lua object.)
  322. */
  323. #define obj2gco(v) check_exp((v)->tt >= LUA_TSTRING, &(cast_u(v)->gc))
  324. /* actual number of total bytes allocated */
  325. #define gettotalbytes(g) cast(lu_mem, (g)->totalbytes + (g)->GCdebt)
  326. LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);
  327. LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
  328. LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
  329. LUAI_FUNC void luaE_freeCI (lua_State *L);
  330. LUAI_FUNC void luaE_shrinkCI (lua_State *L);
  331. LUAI_FUNC void luaE_enterCcall (lua_State *L);
  332. LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont);
  333. LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where);
  334. #define luaE_exitCcall(L) ((L)->nCcalls++)
  335. #endif