2
0

lstate.h 16 KB

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