lstate.h 15 KB

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