9
3

lstate.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. */
  127. typedef struct CallInfo {
  128. StkId func; /* function index in the stack */
  129. StkId top; /* top for this function */
  130. struct CallInfo *previous, *next; /* dynamic call link */
  131. union {
  132. struct { /* only for Lua functions */
  133. const Instruction *savedpc;
  134. volatile l_signalT trap;
  135. int nextraargs; /* # of extra arguments in vararg functions */
  136. } l;
  137. struct { /* only for C functions */
  138. lua_KFunction k; /* continuation in case of yields */
  139. ptrdiff_t old_errfunc;
  140. lua_KContext ctx; /* context info. in case of yields */
  141. } c;
  142. } u;
  143. union {
  144. int funcidx; /* called-function index */
  145. int nyield; /* number of values yielded */
  146. struct { /* info about transferred values (for call/return hooks) */
  147. unsigned short ftransfer; /* offset of first value transferred */
  148. unsigned short ntransfer; /* number of values transferred */
  149. } transferinfo;
  150. } u2;
  151. short nresults; /* expected number of results from this function */
  152. unsigned short callstatus;
  153. } CallInfo;
  154. /*
  155. ** Bits in CallInfo status
  156. */
  157. #define CIST_OAH (1<<0) /* original value of 'allowhook' */
  158. #define CIST_C (1<<1) /* call is running a C function */
  159. #define CIST_FRESH (1<<2) /* call is on a fresh "luaV_execute" frame */
  160. #define CIST_HOOKED (1<<3) /* call is running a debug hook */
  161. #define CIST_YPCALL (1<<4) /* call is a yieldable protected call */
  162. #define CIST_TAIL (1<<5) /* call was tail called */
  163. #define CIST_HOOKYIELD (1<<6) /* last hook called yielded */
  164. #define CIST_FIN (1<<7) /* call is running a finalizer */
  165. #define CIST_TRAN (1<<8) /* 'ci' has transfer information */
  166. #if defined(LUA_COMPAT_LT_LE)
  167. #define CIST_LEQ (1<<9) /* using __lt for __le */
  168. #endif
  169. /* active function is a Lua function */
  170. #define isLua(ci) (!((ci)->callstatus & CIST_C))
  171. /* call is running Lua code (not a hook) */
  172. #define isLuacode(ci) (!((ci)->callstatus & (CIST_C | CIST_HOOKED)))
  173. /* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */
  174. #define setoah(st,v) ((st) = ((st) & ~CIST_OAH) | (v))
  175. #define getoah(st) ((st) & CIST_OAH)
  176. /*
  177. ** 'global state', shared by all threads of this state
  178. */
  179. typedef struct global_State {
  180. lua_Alloc frealloc; /* function to reallocate memory */
  181. void *ud; /* auxiliary data to 'frealloc' */
  182. l_mem totalbytes; /* number of bytes currently allocated - GCdebt */
  183. l_mem GCdebt; /* bytes allocated not yet compensated by the collector */
  184. lu_mem GCestimate; /* an estimate of the non-garbage memory in use */
  185. lu_mem lastatomic; /* see function 'genstep' in file 'lgc.c' */
  186. stringtable strt; /* hash table for strings */
  187. TValue l_registry;
  188. TValue nilvalue; /* a nil value */
  189. unsigned int seed; /* randomized seed for hashes */
  190. lu_byte currentwhite;
  191. lu_byte gcstate; /* state of garbage collector */
  192. lu_byte gckind; /* kind of GC running */
  193. lu_byte genminormul; /* control for minor generational collections */
  194. lu_byte genmajormul; /* control for major generational collections */
  195. lu_byte gcrunning; /* true if GC is running */
  196. lu_byte gcemergency; /* true if this is an emergency collection */
  197. lu_byte gcpause; /* size of pause between successive GCs */
  198. lu_byte gcstepmul; /* GC "speed" */
  199. lu_byte gcstepsize; /* (log2 of) GC granularity */
  200. GCObject *allgc; /* list of all collectable objects */
  201. GCObject **sweepgc; /* current position of sweep in list */
  202. GCObject *finobj; /* list of collectable objects with finalizers */
  203. GCObject *gray; /* list of gray objects */
  204. GCObject *grayagain; /* list of objects to be traversed atomically */
  205. GCObject *weak; /* list of tables with weak values */
  206. GCObject *ephemeron; /* list of ephemeron tables (weak keys) */
  207. GCObject *allweak; /* list of all-weak tables */
  208. GCObject *tobefnz; /* list of userdata to be GC */
  209. GCObject *fixedgc; /* list of objects not to be collected */
  210. /* fields for generational collector */
  211. GCObject *survival; /* start of objects that survived one GC cycle */
  212. GCObject *old1; /* start of old1 objects */
  213. GCObject *reallyold; /* objects more than one cycle old ("really old") */
  214. GCObject *firstold1; /* first OLD1 object in the list (if any) */
  215. GCObject *finobjsur; /* list of survival objects with finalizers */
  216. GCObject *finobjold1; /* list of old1 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. } global_State;
  228. /*
  229. ** 'per thread' state
  230. */
  231. struct lua_State {
  232. CommonHeader;
  233. lu_byte status;
  234. lu_byte allowhook;
  235. unsigned short nci; /* number of items in 'ci' list */
  236. StkId top; /* first free slot in the stack */
  237. global_State *l_G;
  238. CallInfo *ci; /* call info for current function */
  239. StkId stack_last; /* end of stack (last element + 1) */
  240. StkId stack; /* stack base */
  241. UpVal *openupval; /* list of open upvalues in this stack */
  242. GCObject *gclist;
  243. struct lua_State *twups; /* list of threads with open upvalues */
  244. struct lua_longjmp *errorJmp; /* current error recover point */
  245. CallInfo base_ci; /* CallInfo for first level (C calling Lua) */
  246. volatile lua_Hook hook;
  247. ptrdiff_t errfunc; /* current error handling function (stack index) */
  248. l_uint32 nCcalls; /* number of nested (non-yieldable | C) calls */
  249. int oldpc; /* last pc traced */
  250. int basehookcount;
  251. int hookcount;
  252. volatile l_signalT hookmask;
  253. };
  254. #define G(L) (L->l_G)
  255. /*
  256. ** Union of all collectable objects (only for conversions)
  257. ** ISO C99, 6.5.2.3 p.5:
  258. ** "if a union contains several structures that share a common initial
  259. ** sequence [...], and if the union object currently contains one
  260. ** of these structures, it is permitted to inspect the common initial
  261. ** part of any of them anywhere that a declaration of the complete type
  262. ** of the union is visible."
  263. */
  264. union GCUnion {
  265. GCObject gc; /* common header */
  266. struct TString ts;
  267. struct Udata u;
  268. union Closure cl;
  269. struct Table h;
  270. struct Proto p;
  271. struct lua_State th; /* thread */
  272. struct UpVal upv;
  273. };
  274. /*
  275. ** ISO C99, 6.7.2.1 p.14:
  276. ** "A pointer to a union object, suitably converted, points to each of
  277. ** its members [...], and vice versa."
  278. */
  279. #define cast_u(o) cast(union GCUnion *, (o))
  280. /* macros to convert a GCObject into a specific value */
  281. #define gco2ts(o) \
  282. check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))
  283. #define gco2u(o) check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u))
  284. #define gco2lcl(o) check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l))
  285. #define gco2ccl(o) check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c))
  286. #define gco2cl(o) \
  287. check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))
  288. #define gco2t(o) check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h))
  289. #define gco2p(o) check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p))
  290. #define gco2th(o) check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th))
  291. #define gco2upv(o) check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv))
  292. /*
  293. ** macro to convert a Lua object into a GCObject
  294. ** (The access to 'tt' tries to ensure that 'v' is actually a Lua object.)
  295. */
  296. #define obj2gco(v) check_exp((v)->tt >= LUA_TSTRING, &(cast_u(v)->gc))
  297. /* actual number of total bytes allocated */
  298. #define gettotalbytes(g) cast(lu_mem, (g)->totalbytes + (g)->GCdebt)
  299. LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);
  300. LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
  301. LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
  302. LUAI_FUNC void luaE_freeCI (lua_State *L);
  303. LUAI_FUNC void luaE_shrinkCI (lua_State *L);
  304. LUAI_FUNC void luaE_checkcstack (lua_State *L);
  305. LUAI_FUNC void luaE_incCstack (lua_State *L);
  306. LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont);
  307. LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where);
  308. #endif