Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-07 10:37:57

0001 /*
0002 ** $Id: lstate.h $
0003 ** Global State
0004 ** See Copyright Notice in lua.h
0005 */
0006 
0007 #ifndef lstate_h
0008 #define lstate_h
0009 
0010 #include "lua.h"
0011 
0012 
0013 /* Some header files included here need this definition */
0014 typedef struct CallInfo CallInfo;
0015 
0016 
0017 #include "lobject.h"
0018 #include "ltm.h"
0019 #include "lzio.h"
0020 
0021 
0022 /*
0023 ** Some notes about garbage-collected objects: All objects in Lua must
0024 ** be kept somehow accessible until being freed, so all objects always
0025 ** belong to one (and only one) of these lists, using field 'next' of
0026 ** the 'CommonHeader' for the link:
0027 **
0028 ** 'allgc': all objects not marked for finalization;
0029 ** 'finobj': all objects marked for finalization;
0030 ** 'tobefnz': all objects ready to be finalized;
0031 ** 'fixedgc': all objects that are not to be collected (currently
0032 ** only small strings, such as reserved words).
0033 **
0034 ** For the generational collector, some of these lists have marks for
0035 ** generations. Each mark points to the first element in the list for
0036 ** that particular generation; that generation goes until the next mark.
0037 **
0038 ** 'allgc' -> 'survival': new objects;
0039 ** 'survival' -> 'old': objects that survived one collection;
0040 ** 'old1' -> 'reallyold': objects that became old in last collection;
0041 ** 'reallyold' -> NULL: objects old for more than one cycle.
0042 **
0043 ** 'finobj' -> 'finobjsur': new objects marked for finalization;
0044 ** 'finobjsur' -> 'finobjold1': survived   """";
0045 ** 'finobjold1' -> 'finobjrold': just old  """";
0046 ** 'finobjrold' -> NULL: really old       """".
0047 **
0048 ** All lists can contain elements older than their main ages, due
0049 ** to 'luaC_checkfinalizer' and 'udata2finalize', which move
0050 ** objects between the normal lists and the "marked for finalization"
0051 ** lists. Moreover, barriers can age young objects in young lists as
0052 ** OLD0, which then become OLD1. However, a list never contains
0053 ** elements younger than their main ages.
0054 **
0055 ** The generational collector also uses a pointer 'firstold1', which
0056 ** points to the first OLD1 object in the list. It is used to optimize
0057 ** 'markold'. (Potentially OLD1 objects can be anywhere between 'allgc'
0058 ** and 'reallyold', but often the list has no OLD1 objects or they are
0059 ** after 'old1'.) Note the difference between it and 'old1':
0060 ** 'firstold1': no OLD1 objects before this point; there can be all
0061 **   ages after it.
0062 ** 'old1': no objects younger than OLD1 after this point.
0063 */
0064 
0065 /*
0066 ** Moreover, there is another set of lists that control gray objects.
0067 ** These lists are linked by fields 'gclist'. (All objects that
0068 ** can become gray have such a field. The field is not the same
0069 ** in all objects, but it always has this name.)  Any gray object
0070 ** must belong to one of these lists, and all objects in these lists
0071 ** must be gray (with two exceptions explained below):
0072 **
0073 ** 'gray': regular gray objects, still waiting to be visited.
0074 ** 'grayagain': objects that must be revisited at the atomic phase.
0075 **   That includes
0076 **   - black objects got in a write barrier;
0077 **   - all kinds of weak tables during propagation phase;
0078 **   - all threads.
0079 ** 'weak': tables with weak values to be cleared;
0080 ** 'ephemeron': ephemeron tables with white->white entries;
0081 ** 'allweak': tables with weak keys and/or weak values to be cleared.
0082 **
0083 ** The exceptions to that "gray rule" are:
0084 ** - TOUCHED2 objects in generational mode stay in a gray list (because
0085 ** they must be visited again at the end of the cycle), but they are
0086 ** marked black because assignments to them must activate barriers (to
0087 ** move them back to TOUCHED1).
0088 ** - Open upvales are kept gray to avoid barriers, but they stay out
0089 ** of gray lists. (They don't even have a 'gclist' field.)
0090 */
0091 
0092 
0093 
0094 /*
0095 ** About 'nCcalls':  This count has two parts: the lower 16 bits counts
0096 ** the number of recursive invocations in the C stack; the higher
0097 ** 16 bits counts the number of non-yieldable calls in the stack.
0098 ** (They are together so that we can change and save both with one
0099 ** instruction.)
0100 */
0101 
0102 
0103 /* true if this thread does not have non-yieldable calls in the stack */
0104 #define yieldable(L)        (((L)->nCcalls & 0xffff0000) == 0)
0105 
0106 /* real number of C calls */
0107 #define getCcalls(L)    ((L)->nCcalls & 0xffff)
0108 
0109 
0110 /* Increment the number of non-yieldable calls */
0111 #define incnny(L)   ((L)->nCcalls += 0x10000)
0112 
0113 /* Decrement the number of non-yieldable calls */
0114 #define decnny(L)   ((L)->nCcalls -= 0x10000)
0115 
0116 /* Non-yieldable call increment */
0117 #define nyci    (0x10000 | 1)
0118 
0119 
0120 
0121 
0122 struct lua_longjmp;  /* defined in ldo.c */
0123 
0124 
0125 /*
0126 ** Atomic type (relative to signals) to better ensure that 'lua_sethook'
0127 ** is thread safe
0128 */
0129 #if !defined(l_signalT)
0130 #include <signal.h>
0131 #define l_signalT   sig_atomic_t
0132 #endif
0133 
0134 
0135 /*
0136 ** Extra stack space to handle TM calls and some other extras. This
0137 ** space is not included in 'stack_last'. It is used only to avoid stack
0138 ** checks, either because the element will be promptly popped or because
0139 ** there will be a stack check soon after the push. Function frames
0140 ** never use this extra space, so it does not need to be kept clean.
0141 */
0142 #define EXTRA_STACK   5
0143 
0144 
0145 #define BASIC_STACK_SIZE        (2*LUA_MINSTACK)
0146 
0147 #define stacksize(th)   cast_int((th)->stack_last.p - (th)->stack.p)
0148 
0149 
0150 /* kinds of Garbage Collection */
0151 #define KGC_INC     0   /* incremental gc */
0152 #define KGC_GEN     1   /* generational gc */
0153 
0154 
0155 typedef struct stringtable {
0156   TString **hash;
0157   int nuse;  /* number of elements */
0158   int size;
0159 } stringtable;
0160 
0161 
0162 /*
0163 ** Information about a call.
0164 ** About union 'u':
0165 ** - field 'l' is used only for Lua functions;
0166 ** - field 'c' is used only for C functions.
0167 ** About union 'u2':
0168 ** - field 'funcidx' is used only by C functions while doing a
0169 ** protected call;
0170 ** - field 'nyield' is used only while a function is "doing" an
0171 ** yield (from the yield until the next resume);
0172 ** - field 'nres' is used only while closing tbc variables when
0173 ** returning from a function;
0174 ** - field 'transferinfo' is used only during call/returnhooks,
0175 ** before the function starts or after it ends.
0176 */
0177 struct CallInfo {
0178   StkIdRel func;  /* function index in the stack */
0179   StkIdRel  top;  /* top for this function */
0180   struct CallInfo *previous, *next;  /* dynamic call link */
0181   union {
0182     struct {  /* only for Lua functions */
0183       const Instruction *savedpc;
0184       volatile l_signalT trap;  /* function is tracing lines/counts */
0185       int nextraargs;  /* # of extra arguments in vararg functions */
0186     } l;
0187     struct {  /* only for C functions */
0188       lua_KFunction k;  /* continuation in case of yields */
0189       ptrdiff_t old_errfunc;
0190       lua_KContext ctx;  /* context info. in case of yields */
0191     } c;
0192   } u;
0193   union {
0194     int funcidx;  /* called-function index */
0195     int nyield;  /* number of values yielded */
0196     int nres;  /* number of values returned */
0197     struct {  /* info about transferred values (for call/return hooks) */
0198       unsigned short ftransfer;  /* offset of first value transferred */
0199       unsigned short ntransfer;  /* number of values transferred */
0200     } transferinfo;
0201   } u2;
0202   short nresults;  /* expected number of results from this function */
0203   unsigned short callstatus;
0204 };
0205 
0206 
0207 /*
0208 ** Bits in CallInfo status
0209 */
0210 #define CIST_OAH    (1<<0)  /* original value of 'allowhook' */
0211 #define CIST_C      (1<<1)  /* call is running a C function */
0212 #define CIST_FRESH  (1<<2)  /* call is on a fresh "luaV_execute" frame */
0213 #define CIST_HOOKED (1<<3)  /* call is running a debug hook */
0214 #define CIST_YPCALL (1<<4)  /* doing a yieldable protected call */
0215 #define CIST_TAIL   (1<<5)  /* call was tail called */
0216 #define CIST_HOOKYIELD  (1<<6)  /* last hook called yielded */
0217 #define CIST_FIN    (1<<7)  /* function "called" a finalizer */
0218 #define CIST_TRAN   (1<<8)  /* 'ci' has transfer information */
0219 #define CIST_CLSRET (1<<9)  /* function is closing tbc variables */
0220 /* Bits 10-12 are used for CIST_RECST (see below) */
0221 #define CIST_RECST  10
0222 #if defined(LUA_COMPAT_LT_LE)
0223 #define CIST_LEQ    (1<<13)  /* using __lt for __le */
0224 #endif
0225 
0226 
0227 /*
0228 ** Field CIST_RECST stores the "recover status", used to keep the error
0229 ** status while closing to-be-closed variables in coroutines, so that
0230 ** Lua can correctly resume after an yield from a __close method called
0231 ** because of an error.  (Three bits are enough for error status.)
0232 */
0233 #define getcistrecst(ci)     (((ci)->callstatus >> CIST_RECST) & 7)
0234 #define setcistrecst(ci,st)  \
0235   check_exp(((st) & 7) == (st),   /* status must fit in three bits */  \
0236             ((ci)->callstatus = ((ci)->callstatus & ~(7 << CIST_RECST))  \
0237                                                   | ((st) << CIST_RECST)))
0238 
0239 
0240 /* active function is a Lua function */
0241 #define isLua(ci)   (!((ci)->callstatus & CIST_C))
0242 
0243 /* call is running Lua code (not a hook) */
0244 #define isLuacode(ci)   (!((ci)->callstatus & (CIST_C | CIST_HOOKED)))
0245 
0246 /* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */
0247 #define setoah(st,v)    ((st) = ((st) & ~CIST_OAH) | (v))
0248 #define getoah(st)  ((st) & CIST_OAH)
0249 
0250 
0251 /*
0252 ** 'global state', shared by all threads of this state
0253 */
0254 typedef struct global_State {
0255   lua_Alloc frealloc;  /* function to reallocate memory */
0256   void *ud;         /* auxiliary data to 'frealloc' */
0257   l_mem totalbytes;  /* number of bytes currently allocated - GCdebt */
0258   l_mem GCdebt;  /* bytes allocated not yet compensated by the collector */
0259   lu_mem GCestimate;  /* an estimate of the non-garbage memory in use */
0260   lu_mem lastatomic;  /* see function 'genstep' in file 'lgc.c' */
0261   stringtable strt;  /* hash table for strings */
0262   TValue l_registry;
0263   TValue nilvalue;  /* a nil value */
0264   unsigned int seed;  /* randomized seed for hashes */
0265   lu_byte currentwhite;
0266   lu_byte gcstate;  /* state of garbage collector */
0267   lu_byte gckind;  /* kind of GC running */
0268   lu_byte gcstopem;  /* stops emergency collections */
0269   lu_byte genminormul;  /* control for minor generational collections */
0270   lu_byte genmajormul;  /* control for major generational collections */
0271   lu_byte gcstp;  /* control whether GC is running */
0272   lu_byte gcemergency;  /* true if this is an emergency collection */
0273   lu_byte gcpause;  /* size of pause between successive GCs */
0274   lu_byte gcstepmul;  /* GC "speed" */
0275   lu_byte gcstepsize;  /* (log2 of) GC granularity */
0276   GCObject *allgc;  /* list of all collectable objects */
0277   GCObject **sweepgc;  /* current position of sweep in list */
0278   GCObject *finobj;  /* list of collectable objects with finalizers */
0279   GCObject *gray;  /* list of gray objects */
0280   GCObject *grayagain;  /* list of objects to be traversed atomically */
0281   GCObject *weak;  /* list of tables with weak values */
0282   GCObject *ephemeron;  /* list of ephemeron tables (weak keys) */
0283   GCObject *allweak;  /* list of all-weak tables */
0284   GCObject *tobefnz;  /* list of userdata to be GC */
0285   GCObject *fixedgc;  /* list of objects not to be collected */
0286   /* fields for generational collector */
0287   GCObject *survival;  /* start of objects that survived one GC cycle */
0288   GCObject *old1;  /* start of old1 objects */
0289   GCObject *reallyold;  /* objects more than one cycle old ("really old") */
0290   GCObject *firstold1;  /* first OLD1 object in the list (if any) */
0291   GCObject *finobjsur;  /* list of survival objects with finalizers */
0292   GCObject *finobjold1;  /* list of old1 objects with finalizers */
0293   GCObject *finobjrold;  /* list of really old objects with finalizers */
0294   struct lua_State *twups;  /* list of threads with open upvalues */
0295   lua_CFunction panic;  /* to be called in unprotected errors */
0296   struct lua_State *mainthread;
0297   TString *memerrmsg;  /* message for memory-allocation errors */
0298   TString *tmname[TM_N];  /* array with tag-method names */
0299   struct Table *mt[LUA_NUMTYPES];  /* metatables for basic types */
0300   TString *strcache[STRCACHE_N][STRCACHE_M];  /* cache for strings in API */
0301   lua_WarnFunction warnf;  /* warning function */
0302   void *ud_warn;         /* auxiliary data to 'warnf' */
0303 } global_State;
0304 
0305 
0306 /*
0307 ** 'per thread' state
0308 */
0309 struct lua_State {
0310   CommonHeader;
0311   lu_byte status;
0312   lu_byte allowhook;
0313   unsigned short nci;  /* number of items in 'ci' list */
0314   StkIdRel top;  /* first free slot in the stack */
0315   global_State *l_G;
0316   CallInfo *ci;  /* call info for current function */
0317   StkIdRel stack_last;  /* end of stack (last element + 1) */
0318   StkIdRel stack;  /* stack base */
0319   UpVal *openupval;  /* list of open upvalues in this stack */
0320   StkIdRel tbclist;  /* list of to-be-closed variables */
0321   GCObject *gclist;
0322   struct lua_State *twups;  /* list of threads with open upvalues */
0323   struct lua_longjmp *errorJmp;  /* current error recover point */
0324   CallInfo base_ci;  /* CallInfo for first level (C calling Lua) */
0325   volatile lua_Hook hook;
0326   ptrdiff_t errfunc;  /* current error handling function (stack index) */
0327   l_uint32 nCcalls;  /* number of nested (non-yieldable | C)  calls */
0328   int oldpc;  /* last pc traced */
0329   int basehookcount;
0330   int hookcount;
0331   volatile l_signalT hookmask;
0332 };
0333 
0334 
0335 #define G(L)    (L->l_G)
0336 
0337 /*
0338 ** 'g->nilvalue' being a nil value flags that the state was completely
0339 ** build.
0340 */
0341 #define completestate(g)    ttisnil(&g->nilvalue)
0342 
0343 
0344 /*
0345 ** Union of all collectable objects (only for conversions)
0346 ** ISO C99, 6.5.2.3 p.5:
0347 ** "if a union contains several structures that share a common initial
0348 ** sequence [...], and if the union object currently contains one
0349 ** of these structures, it is permitted to inspect the common initial
0350 ** part of any of them anywhere that a declaration of the complete type
0351 ** of the union is visible."
0352 */
0353 union GCUnion {
0354   GCObject gc;  /* common header */
0355   struct TString ts;
0356   struct Udata u;
0357   union Closure cl;
0358   struct Table h;
0359   struct Proto p;
0360   struct lua_State th;  /* thread */
0361   struct UpVal upv;
0362 };
0363 
0364 
0365 /*
0366 ** ISO C99, 6.7.2.1 p.14:
0367 ** "A pointer to a union object, suitably converted, points to each of
0368 ** its members [...], and vice versa."
0369 */
0370 #define cast_u(o)   cast(union GCUnion *, (o))
0371 
0372 /* macros to convert a GCObject into a specific value */
0373 #define gco2ts(o)  \
0374     check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))
0375 #define gco2u(o)  check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u))
0376 #define gco2lcl(o)  check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l))
0377 #define gco2ccl(o)  check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c))
0378 #define gco2cl(o)  \
0379     check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))
0380 #define gco2t(o)  check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h))
0381 #define gco2p(o)  check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p))
0382 #define gco2th(o)  check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th))
0383 #define gco2upv(o)  check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv))
0384 
0385 
0386 /*
0387 ** macro to convert a Lua object into a GCObject
0388 ** (The access to 'tt' tries to ensure that 'v' is actually a Lua object.)
0389 */
0390 #define obj2gco(v)  check_exp((v)->tt >= LUA_TSTRING, &(cast_u(v)->gc))
0391 
0392 
0393 /* actual number of total bytes allocated */
0394 #define gettotalbytes(g)    cast(lu_mem, (g)->totalbytes + (g)->GCdebt)
0395 
0396 LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);
0397 LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
0398 LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
0399 LUAI_FUNC void luaE_shrinkCI (lua_State *L);
0400 LUAI_FUNC void luaE_checkcstack (lua_State *L);
0401 LUAI_FUNC void luaE_incCstack (lua_State *L);
0402 LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont);
0403 LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where);
0404 LUAI_FUNC int luaE_resetthread (lua_State *L, int status);
0405 
0406 
0407 #endif
0408