lstate.h 15 KB

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