lstate.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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_GEN 1 /* generational gc */
  121. typedef struct stringtable {
  122. TString **hash;
  123. int nuse; /* number of elements */
  124. int size;
  125. } stringtable;
  126. /*
  127. ** Information about a call.
  128. ** About union 'u':
  129. ** - field 'l' is used only for Lua functions;
  130. ** - field 'c' is used only for C functions.
  131. ** About union 'u2':
  132. ** - field 'funcidx' is used only by C functions while doing a
  133. ** protected call;
  134. ** - field 'nyield' is used only while a function is "doing" an
  135. ** yield (from the yield until the next resume);
  136. ** - field 'nres' is used only while closing tbc variables when
  137. ** returning from a function;
  138. ** - field 'transferinfo' is used only during call/returnhooks,
  139. ** before the function starts or after it ends.
  140. */
  141. struct CallInfo {
  142. StkIdRel func; /* function index in the stack */
  143. StkIdRel top; /* top for this function */
  144. struct CallInfo *previous, *next; /* dynamic call link */
  145. union {
  146. struct { /* only for Lua functions */
  147. const Instruction *savedpc;
  148. volatile l_signalT trap;
  149. int nextraargs; /* # of extra arguments in vararg functions */
  150. } l;
  151. struct { /* only for C functions */
  152. lua_KFunction k; /* continuation in case of yields */
  153. ptrdiff_t old_errfunc;
  154. lua_KContext ctx; /* context info. in case of yields */
  155. } c;
  156. } u;
  157. union {
  158. int funcidx; /* called-function index */
  159. int nyield; /* number of values yielded */
  160. int nres; /* number of values returned */
  161. struct { /* info about transferred values (for call/return hooks) */
  162. unsigned short ftransfer; /* offset of first value transferred */
  163. unsigned short ntransfer; /* number of values transferred */
  164. } transferinfo;
  165. } u2;
  166. short nresults; /* expected number of results from this function */
  167. unsigned short callstatus;
  168. };
  169. /*
  170. ** Bits in CallInfo status
  171. */
  172. #define CIST_OAH (1<<0) /* original value of 'allowhook' */
  173. #define CIST_C (1<<1) /* call is running a C function */
  174. #define CIST_FRESH (1<<2) /* call is on a fresh "luaV_execute" frame */
  175. #define CIST_HOOKED (1<<3) /* call is running a debug hook */
  176. #define CIST_YPCALL (1<<4) /* doing a yieldable protected call */
  177. #define CIST_TAIL (1<<5) /* call was tail called */
  178. #define CIST_HOOKYIELD (1<<6) /* last hook called yielded */
  179. #define CIST_FIN (1<<7) /* function "called" a finalizer */
  180. #define CIST_TRAN (1<<8) /* 'ci' has transfer information */
  181. #define CIST_CLSRET (1<<9) /* function is closing tbc variables */
  182. /* Bits 10-12 are used for CIST_RECST (see below) */
  183. #define CIST_RECST 10
  184. #if defined(LUA_COMPAT_LT_LE)
  185. #define CIST_LEQ (1<<13) /* using __lt for __le */
  186. #endif
  187. /*
  188. ** Field CIST_RECST stores the "recover status", used to keep the error
  189. ** status while closing to-be-closed variables in coroutines, so that
  190. ** Lua can correctly resume after an yield from a __close method called
  191. ** because of an error. (Three bits are enough for error status.)
  192. */
  193. #define getcistrecst(ci) (((ci)->callstatus >> CIST_RECST) & 7)
  194. #define setcistrecst(ci,st) \
  195. check_exp(((st) & 7) == (st), /* status must fit in three bits */ \
  196. ((ci)->callstatus = ((ci)->callstatus & ~(7 << CIST_RECST)) \
  197. | ((st) << CIST_RECST)))
  198. /* active function is a Lua function */
  199. #define isLua(ci) (!((ci)->callstatus & CIST_C))
  200. /* call is running Lua code (not a hook) */
  201. #define isLuacode(ci) (!((ci)->callstatus & (CIST_C | CIST_HOOKED)))
  202. /* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */
  203. #define setoah(st,v) ((st) = ((st) & ~CIST_OAH) | (v))
  204. #define getoah(st) ((st) & CIST_OAH)
  205. /*
  206. ** 'global state', shared by all threads of this state
  207. */
  208. typedef struct global_State {
  209. lua_Alloc frealloc; /* function to reallocate memory */
  210. void *ud; /* auxiliary data to 'frealloc' */
  211. l_mem totalbytes; /* number of bytes currently allocated - GCdebt */
  212. l_mem GCdebt; /* bytes allocated not yet compensated by the collector */
  213. lu_mem GCestimate; /* an estimate of the non-garbage memory in use */
  214. lu_mem lastatomic; /* see function 'genstep' in file 'lgc.c' */
  215. stringtable strt; /* hash table for strings */
  216. TValue l_registry;
  217. TValue nilvalue; /* a nil value */
  218. lu_byte currentwhite;
  219. lu_byte gcstate; /* state of garbage collector */
  220. lu_byte gckind; /* kind of GC running */
  221. lu_byte gcstopem; /* stops emergency collections */
  222. lu_byte genminormul; /* control for minor generational collections */
  223. lu_byte genmajormul; /* control for major generational collections */
  224. lu_byte gcstp; /* control whether GC is running */
  225. lu_byte gcemergency; /* true if this is an emergency collection */
  226. lu_byte gcpause; /* size of pause between successive GCs */
  227. lu_byte gcstepmul; /* GC "speed" */
  228. lu_byte gcstepsize; /* (log2 of) GC granularity */
  229. GCObject *allgc; /* list of all collectable objects */
  230. GCObject **sweepgc; /* current position of sweep in list */
  231. GCObject *finobj; /* list of collectable objects with finalizers */
  232. GCObject *gray; /* list of gray objects */
  233. GCObject *grayagain; /* list of objects to be traversed atomically */
  234. GCObject *weak; /* list of tables with weak values */
  235. GCObject *ephemeron; /* list of ephemeron tables (weak keys) */
  236. GCObject *allweak; /* list of all-weak tables */
  237. GCObject *tobefnz; /* list of userdata to be GC */
  238. GCObject *fixedgc; /* list of objects not to be collected */
  239. /* fields for generational collector */
  240. GCObject *survival; /* start of objects that survived one GC cycle */
  241. GCObject *old1; /* start of old1 objects */
  242. GCObject *reallyold; /* objects more than one cycle old ("really old") */
  243. GCObject *firstold1; /* first OLD1 object in the list (if any) */
  244. GCObject *finobjsur; /* list of survival objects with finalizers */
  245. GCObject *finobjold1; /* list of old1 objects with finalizers */
  246. GCObject *finobjrold; /* list of really old objects with finalizers */
  247. struct lua_State *twups; /* list of threads with open upvalues */
  248. lua_CFunction panic; /* to be called in unprotected errors */
  249. struct lua_State *mainthread;
  250. TString *memerrmsg; /* message for memory-allocation errors */
  251. TString *tmname[TM_N]; /* array with tag-method names */
  252. struct Table *mt[LUA_NUMTYPES]; /* metatables for basic types */
  253. TString *strcache[STRCACHE_N][STRCACHE_M]; /* cache for strings in API */
  254. lua_WarnFunction warnf; /* warning function */
  255. void *ud_warn; /* auxiliary data to 'warnf' */
  256. } global_State;
  257. /*
  258. ** 'per thread' state
  259. */
  260. struct lua_State {
  261. CommonHeader;
  262. lu_byte status;
  263. lu_byte allowhook;
  264. unsigned short nci; /* number of items in 'ci' list */
  265. StkIdRel top; /* first free slot in the stack */
  266. global_State *l_G;
  267. CallInfo *ci; /* call info for current function */
  268. StkIdRel stack_last; /* end of stack (last element + 1) */
  269. StkIdRel stack; /* stack base */
  270. UpVal *openupval; /* list of open upvalues in this stack */
  271. StkIdRel tbclist; /* list of to-be-closed variables */
  272. GCObject *gclist;
  273. struct lua_State *twups; /* list of threads with open upvalues */
  274. struct lua_longjmp *errorJmp; /* current error recover point */
  275. CallInfo base_ci; /* CallInfo for first level (C calling Lua) */
  276. volatile lua_Hook hook;
  277. ptrdiff_t errfunc; /* current error handling function (stack index) */
  278. l_uint32 nCcalls; /* number of nested (non-yieldable | C) calls */
  279. int oldpc; /* last pc traced */
  280. int basehookcount;
  281. int hookcount;
  282. volatile l_signalT hookmask;
  283. };
  284. #define G(L) (L->l_G)
  285. /*
  286. ** 'g->nilvalue' being a nil value flags that the state was completely
  287. ** build.
  288. */
  289. #define completestate(g) ttisnil(&g->nilvalue)
  290. /*
  291. ** Union of all collectable objects (only for conversions)
  292. ** ISO C99, 6.5.2.3 p.5:
  293. ** "if a union contains several structures that share a common initial
  294. ** sequence [...], and if the union object currently contains one
  295. ** of these structures, it is permitted to inspect the common initial
  296. ** part of any of them anywhere that a declaration of the complete type
  297. ** of the union is visible."
  298. */
  299. union GCUnion {
  300. GCObject gc; /* common header */
  301. struct TString ts;
  302. struct Udata u;
  303. union Closure cl;
  304. struct Table h;
  305. struct Proto p;
  306. struct lua_State th; /* thread */
  307. struct UpVal upv;
  308. };
  309. /*
  310. ** ISO C99, 6.7.2.1 p.14:
  311. ** "A pointer to a union object, suitably converted, points to each of
  312. ** its members [...], and vice versa."
  313. */
  314. #define cast_u(o) cast(union GCUnion *, (o))
  315. /* macros to convert a GCObject into a specific value */
  316. #define gco2ts(o) \
  317. check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))
  318. #define gco2u(o) check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u))
  319. #define gco2lcl(o) check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l))
  320. #define gco2ccl(o) check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c))
  321. #define gco2cl(o) \
  322. check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))
  323. #define gco2t(o) check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h))
  324. #define gco2p(o) check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p))
  325. #define gco2th(o) check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th))
  326. #define gco2upv(o) check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv))
  327. /*
  328. ** macro to convert a Lua object into a GCObject
  329. ** (The access to 'tt' tries to ensure that 'v' is actually a Lua object.)
  330. */
  331. #define obj2gco(v) check_exp((v)->tt >= LUA_TSTRING, &(cast_u(v)->gc))
  332. /* actual number of total bytes allocated */
  333. #define gettotalbytes(g) cast(lu_mem, (g)->totalbytes + (g)->GCdebt)
  334. LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);
  335. LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
  336. LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
  337. LUAI_FUNC void luaE_freeCI (lua_State *L);
  338. LUAI_FUNC void luaE_shrinkCI (lua_State *L);
  339. LUAI_FUNC void luaE_checkcstack (lua_State *L);
  340. LUAI_FUNC void luaE_incCstack (lua_State *L);
  341. LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont);
  342. LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where);
  343. LUAI_FUNC int luaE_resetthread (lua_State *L, int status);
  344. #endif