lstate.h 13 KB

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