lua

A copy of the Lua development repository
Log | Files | Refs | README

lstate.h (16101B)


      1 /*
      2 ** $Id: lstate.h $
      3 ** Global State
      4 ** See Copyright Notice in lua.h
      5 */
      6 
      7 #ifndef lstate_h
      8 #define lstate_h
      9 
     10 #include "lua.h"
     11 
     12 
     13 /* Some header files included here need this definition */
     14 typedef struct CallInfo CallInfo;
     15 
     16 
     17 #include "lobject.h"
     18 #include "ltm.h"
     19 #include "lzio.h"
     20 
     21 
     22 /*
     23 ** Some notes about garbage-collected objects: All objects in Lua must
     24 ** be kept somehow accessible until being freed, so all objects always
     25 ** belong to one (and only one) of these lists, using field 'next' of
     26 ** the 'CommonHeader' for the link:
     27 **
     28 ** 'allgc': all objects not marked for finalization;
     29 ** 'finobj': all objects marked for finalization;
     30 ** 'tobefnz': all objects ready to be finalized;
     31 ** 'fixedgc': all objects that are not to be collected (currently
     32 ** only small strings, such as reserved words).
     33 **
     34 ** For the generational collector, some of these lists have marks for
     35 ** generations. Each mark points to the first element in the list for
     36 ** that particular generation; that generation goes until the next mark.
     37 **
     38 ** 'allgc' -> 'survival': new objects;
     39 ** 'survival' -> 'old': objects that survived one collection;
     40 ** 'old1' -> 'reallyold': objects that became old in last collection;
     41 ** 'reallyold' -> NULL: objects old for more than one cycle.
     42 **
     43 ** 'finobj' -> 'finobjsur': new objects marked for finalization;
     44 ** 'finobjsur' -> 'finobjold1': survived   """";
     45 ** 'finobjold1' -> 'finobjrold': just old  """";
     46 ** 'finobjrold' -> NULL: really old       """".
     47 **
     48 ** All lists can contain elements older than their main ages, due
     49 ** to 'luaC_checkfinalizer' and 'udata2finalize', which move
     50 ** objects between the normal lists and the "marked for finalization"
     51 ** lists. Moreover, barriers can age young objects in young lists as
     52 ** OLD0, which then become OLD1. However, a list never contains
     53 ** elements younger than their main ages.
     54 **
     55 ** The generational collector also uses a pointer 'firstold1', which
     56 ** points to the first OLD1 object in the list. It is used to optimize
     57 ** 'markold'. (Potentially OLD1 objects can be anywhere between 'allgc'
     58 ** and 'reallyold', but often the list has no OLD1 objects or they are
     59 ** after 'old1'.) Note the difference between it and 'old1':
     60 ** 'firstold1': no OLD1 objects before this point; there can be all
     61 **   ages after it.
     62 ** 'old1': no objects younger than OLD1 after this point.
     63 */
     64 
     65 /*
     66 ** Moreover, there is another set of lists that control gray objects.
     67 ** These lists are linked by fields 'gclist'. (All objects that
     68 ** can become gray have such a field. The field is not the same
     69 ** in all objects, but it always has this name.)  Any gray object
     70 ** must belong to one of these lists, and all objects in these lists
     71 ** must be gray (with two exceptions explained below):
     72 **
     73 ** 'gray': regular gray objects, still waiting to be visited.
     74 ** 'grayagain': objects that must be revisited at the atomic phase.
     75 **   That includes
     76 **   - black objects got in a write barrier;
     77 **   - all kinds of weak tables during propagation phase;
     78 **   - all threads.
     79 ** 'weak': tables with weak values to be cleared;
     80 ** 'ephemeron': ephemeron tables with white->white entries;
     81 ** 'allweak': tables with weak keys and/or weak values to be cleared.
     82 **
     83 ** The exceptions to that "gray rule" are:
     84 ** - TOUCHED2 objects in generational mode stay in a gray list (because
     85 ** they must be visited again at the end of the cycle), but they are
     86 ** marked black because assignments to them must activate barriers (to
     87 ** move them back to TOUCHED1).
     88 ** - Open upvales are kept gray to avoid barriers, but they stay out
     89 ** of gray lists. (They don't even have a 'gclist' field.)
     90 */
     91 
     92 
     93 
     94 /*
     95 ** About 'nCcalls':  This count has two parts: the lower 16 bits counts
     96 ** the number of recursive invocations in the C stack; the higher
     97 ** 16 bits counts the number of non-yieldable calls in the stack.
     98 ** (They are together so that we can change and save both with one
     99 ** instruction.)
    100 */
    101 
    102 
    103 /* true if this thread does not have non-yieldable calls in the stack */
    104 #define yieldable(L)		(((L)->nCcalls & 0xffff0000) == 0)
    105 
    106 /* real number of C calls */
    107 #define getCcalls(L)	((L)->nCcalls & 0xffff)
    108 
    109 
    110 /* Increment the number of non-yieldable calls */
    111 #define incnny(L)	((L)->nCcalls += 0x10000)
    112 
    113 /* Decrement the number of non-yieldable calls */
    114 #define decnny(L)	((L)->nCcalls -= 0x10000)
    115 
    116 /* Non-yieldable call increment */
    117 #define nyci	(0x10000 | 1)
    118 
    119 
    120 
    121 
    122 struct lua_longjmp;  /* defined in ldo.c */
    123 
    124 
    125 /*
    126 ** Atomic type (relative to signals) to better ensure that 'lua_sethook'
    127 ** is thread safe
    128 */
    129 #if !defined(l_signalT)
    130 #include <signal.h>
    131 #define l_signalT	sig_atomic_t
    132 #endif
    133 
    134 
    135 /*
    136 ** Extra stack space to handle TM calls and some other extras. This
    137 ** space is not included in 'stack_last'. It is used only to avoid stack
    138 ** checks, either because the element will be promptly popped or because
    139 ** there will be a stack check soon after the push. Function frames
    140 ** never use this extra space, so it does not need to be kept clean.
    141 */
    142 #define EXTRA_STACK   5
    143 
    144 
    145 /*
    146 ** Size of cache for strings in the API. 'N' is the number of
    147 ** sets (better be a prime) and "M" is the size of each set.
    148 ** (M == 1 makes a direct cache.)
    149 */
    150 #if !defined(STRCACHE_N)
    151 #define STRCACHE_N              53
    152 #define STRCACHE_M              2
    153 #endif
    154 
    155 
    156 #define BASIC_STACK_SIZE        (2*LUA_MINSTACK)
    157 
    158 #define stacksize(th)	cast_int((th)->stack_last.p - (th)->stack.p)
    159 
    160 
    161 /* kinds of Garbage Collection */
    162 #define KGC_INC		0	/* incremental gc */
    163 #define KGC_GENMINOR	1	/* generational gc in minor (regular) mode */
    164 #define KGC_GENMAJOR	2	/* generational in major mode */
    165 
    166 
    167 typedef struct stringtable {
    168   TString **hash;  /* array of buckets (linked lists of strings) */
    169   int nuse;  /* number of elements */
    170   int size;  /* number of buckets */
    171 } stringtable;
    172 
    173 
    174 /*
    175 ** Information about a call.
    176 ** About union 'u':
    177 ** - field 'l' is used only for Lua functions;
    178 ** - field 'c' is used only for C functions.
    179 ** About union 'u2':
    180 ** - field 'funcidx' is used only by C functions while doing a
    181 ** protected call;
    182 ** - field 'nyield' is used only while a function is "doing" an
    183 ** yield (from the yield until the next resume);
    184 ** - field 'nres' is used only while closing tbc variables when
    185 ** returning from a function;
    186 */
    187 struct CallInfo {
    188   StkIdRel func;  /* function index in the stack */
    189   StkIdRel top;  /* top for this function */
    190   struct CallInfo *previous, *next;  /* dynamic call link */
    191   union {
    192     struct {  /* only for Lua functions */
    193       const Instruction *savedpc;
    194       volatile l_signalT trap;  /* function is tracing lines/counts */
    195       int nextraargs;  /* # of extra arguments in vararg functions */
    196     } l;
    197     struct {  /* only for C functions */
    198       lua_KFunction k;  /* continuation in case of yields */
    199       ptrdiff_t old_errfunc;
    200       lua_KContext ctx;  /* context info. in case of yields */
    201     } c;
    202   } u;
    203   union {
    204     int funcidx;  /* called-function index */
    205     int nyield;  /* number of values yielded */
    206     int nres;  /* number of values returned */
    207   } u2;
    208   l_uint32 callstatus;
    209 };
    210 
    211 
    212 /*
    213 ** Maximum expected number of results from a function
    214 ** (must fit in CIST_NRESULTS).
    215 */
    216 #define MAXRESULTS	250
    217 
    218 
    219 /*
    220 ** Bits in CallInfo status
    221 */
    222 /* bits 0-7 are the expected number of results from this function + 1 */
    223 #define CIST_NRESULTS	0xffu
    224 
    225 /* bits 8-11 count call metamethods (and their extra arguments) */
    226 #define CIST_CCMT	8  /* the offset, not the mask */
    227 #define MAX_CCMT	(0xfu << CIST_CCMT)
    228 
    229 /* Bits 12-14 are used for CIST_RECST (see below) */
    230 #define CIST_RECST	12  /* the offset, not the mask */
    231 
    232 /* call is running a C function (still in first 16 bits) */
    233 #define CIST_C		(1u << (CIST_RECST + 3))
    234 /* call is on a fresh "luaV_execute" frame */
    235 #define CIST_FRESH	cast(l_uint32, CIST_C << 1)
    236 /* function is closing tbc variables */
    237 #define CIST_CLSRET	(CIST_FRESH << 1)
    238 /* function has tbc variables to close */
    239 #define CIST_TBC	(CIST_CLSRET << 1)
    240 /* original value of 'allowhook' */
    241 #define CIST_OAH	(CIST_TBC << 1)
    242 /* call is running a debug hook */
    243 #define CIST_HOOKED	(CIST_OAH << 1)
    244 /* doing a yieldable protected call */
    245 #define CIST_YPCALL	(CIST_HOOKED << 1)
    246 /* call was tail called */
    247 #define CIST_TAIL	(CIST_YPCALL << 1)
    248 /* last hook called yielded */
    249 #define CIST_HOOKYIELD	(CIST_TAIL << 1)
    250 /* function "called" a finalizer */
    251 #define CIST_FIN	(CIST_HOOKYIELD << 1)
    252 #if defined(LUA_COMPAT_LT_LE)
    253 /* using __lt for __le */
    254 #define CIST_LEQ	(CIST_FIN << 1)
    255 #endif
    256 
    257 
    258 #define get_nresults(cs)  (cast_int((cs) & CIST_NRESULTS) - 1)
    259 
    260 /*
    261 ** Field CIST_RECST stores the "recover status", used to keep the error
    262 ** status while closing to-be-closed variables in coroutines, so that
    263 ** Lua can correctly resume after an yield from a __close method called
    264 ** because of an error.  (Three bits are enough for error status.)
    265 */
    266 #define getcistrecst(ci)     (((ci)->callstatus >> CIST_RECST) & 7)
    267 #define setcistrecst(ci,st)  \
    268   check_exp(((st) & 7) == (st),   /* status must fit in three bits */  \
    269             ((ci)->callstatus = ((ci)->callstatus & ~(7u << CIST_RECST))  \
    270                                 | (cast(l_uint32, st) << CIST_RECST)))
    271 
    272 
    273 /* active function is a Lua function */
    274 #define isLua(ci)	(!((ci)->callstatus & CIST_C))
    275 
    276 /* call is running Lua code (not a hook) */
    277 #define isLuacode(ci)	(!((ci)->callstatus & (CIST_C | CIST_HOOKED)))
    278 
    279 
    280 #define setoah(ci,v)  \
    281   ((ci)->callstatus = ((v) ? (ci)->callstatus | CIST_OAH  \
    282                            : (ci)->callstatus & ~CIST_OAH))
    283 #define getoah(ci)  (((ci)->callstatus & CIST_OAH) ? 1 : 0)
    284 
    285 
    286 /*
    287 ** 'per thread' state
    288 */
    289 struct lua_State {
    290   CommonHeader;
    291   lu_byte allowhook;
    292   TStatus status;
    293   StkIdRel top;  /* first free slot in the stack */
    294   struct global_State *l_G;
    295   CallInfo *ci;  /* call info for current function */
    296   StkIdRel stack_last;  /* end of stack (last element + 1) */
    297   StkIdRel stack;  /* stack base */
    298   UpVal *openupval;  /* list of open upvalues in this stack */
    299   StkIdRel tbclist;  /* list of to-be-closed variables */
    300   GCObject *gclist;
    301   struct lua_State *twups;  /* list of threads with open upvalues */
    302   struct lua_longjmp *errorJmp;  /* current error recover point */
    303   CallInfo base_ci;  /* CallInfo for first level (C host) */
    304   volatile lua_Hook hook;
    305   ptrdiff_t errfunc;  /* current error handling function (stack index) */
    306   l_uint32 nCcalls;  /* number of nested non-yieldable or C calls */
    307   int oldpc;  /* last pc traced */
    308   int nci;  /* number of items in 'ci' list */
    309   int basehookcount;
    310   int hookcount;
    311   volatile l_signalT hookmask;
    312   struct {  /* info about transferred values (for call/return hooks) */
    313     int ftransfer;  /* offset of first value transferred */
    314     int ntransfer;  /* number of values transferred */
    315   } transferinfo;
    316 };
    317 
    318 
    319 /*
    320 ** thread state + extra space
    321 */
    322 typedef struct LX {
    323   lu_byte extra_[LUA_EXTRASPACE];
    324   lua_State l;
    325 } LX;
    326 
    327 
    328 /*
    329 ** 'global state', shared by all threads of this state
    330 */
    331 typedef struct global_State {
    332   lua_Alloc frealloc;  /* function to reallocate memory */
    333   void *ud;         /* auxiliary data to 'frealloc' */
    334   l_mem GCtotalbytes;  /* number of bytes currently allocated + debt */
    335   l_mem GCdebt;  /* bytes counted but not yet allocated */
    336   l_mem GCmarked;  /* number of objects marked in a GC cycle */
    337   l_mem GCmajorminor;  /* auxiliary counter to control major-minor shifts */
    338   stringtable strt;  /* hash table for strings */
    339   TValue l_registry;
    340   TValue nilvalue;  /* a nil value */
    341   unsigned int seed;  /* randomized seed for hashes */
    342   lu_byte gcparams[LUA_GCPN];
    343   lu_byte currentwhite;
    344   lu_byte gcstate;  /* state of garbage collector */
    345   lu_byte gckind;  /* kind of GC running */
    346   lu_byte gcstopem;  /* stops emergency collections */
    347   lu_byte gcstp;  /* control whether GC is running */
    348   lu_byte gcemergency;  /* true if this is an emergency collection */
    349   GCObject *allgc;  /* list of all collectable objects */
    350   GCObject **sweepgc;  /* current position of sweep in list */
    351   GCObject *finobj;  /* list of collectable objects with finalizers */
    352   GCObject *gray;  /* list of gray objects */
    353   GCObject *grayagain;  /* list of objects to be traversed atomically */
    354   GCObject *weak;  /* list of tables with weak values */
    355   GCObject *ephemeron;  /* list of ephemeron tables (weak keys) */
    356   GCObject *allweak;  /* list of all-weak tables */
    357   GCObject *tobefnz;  /* list of userdata to be GC */
    358   GCObject *fixedgc;  /* list of objects not to be collected */
    359   /* fields for generational collector */
    360   GCObject *survival;  /* start of objects that survived one GC cycle */
    361   GCObject *old1;  /* start of old1 objects */
    362   GCObject *reallyold;  /* objects more than one cycle old ("really old") */
    363   GCObject *firstold1;  /* first OLD1 object in the list (if any) */
    364   GCObject *finobjsur;  /* list of survival objects with finalizers */
    365   GCObject *finobjold1;  /* list of old1 objects with finalizers */
    366   GCObject *finobjrold;  /* list of really old objects with finalizers */
    367   struct lua_State *twups;  /* list of threads with open upvalues */
    368   lua_CFunction panic;  /* to be called in unprotected errors */
    369   TString *memerrmsg;  /* message for memory-allocation errors */
    370   TString *tmname[TM_N];  /* array with tag-method names */
    371   struct Table *mt[LUA_NUMTYPES];  /* metatables for basic types */
    372   TString *strcache[STRCACHE_N][STRCACHE_M];  /* cache for strings in API */
    373   lua_WarnFunction warnf;  /* warning function */
    374   void *ud_warn;         /* auxiliary data to 'warnf' */
    375   LX mainth;  /* main thread of this state */
    376 } global_State;
    377 
    378 
    379 #define G(L)	(L->l_G)
    380 #define mainthread(G)	(&(G)->mainth.l)
    381 
    382 /*
    383 ** 'g->nilvalue' being a nil value flags that the state was completely
    384 ** build.
    385 */
    386 #define completestate(g)	ttisnil(&g->nilvalue)
    387 
    388 
    389 /*
    390 ** Union of all collectable objects (only for conversions)
    391 ** ISO C99, 6.5.2.3 p.5:
    392 ** "if a union contains several structures that share a common initial
    393 ** sequence [...], and if the union object currently contains one
    394 ** of these structures, it is permitted to inspect the common initial
    395 ** part of any of them anywhere that a declaration of the complete type
    396 ** of the union is visible."
    397 */
    398 union GCUnion {
    399   GCObject gc;  /* common header */
    400   struct TString ts;
    401   struct Udata u;
    402   union Closure cl;
    403   struct Table h;
    404   struct Proto p;
    405   struct lua_State th;  /* thread */
    406   struct UpVal upv;
    407 };
    408 
    409 
    410 /*
    411 ** ISO C99, 6.7.2.1 p.14:
    412 ** "A pointer to a union object, suitably converted, points to each of
    413 ** its members [...], and vice versa."
    414 */
    415 #define cast_u(o)	cast(union GCUnion *, (o))
    416 
    417 /* macros to convert a GCObject into a specific value */
    418 #define gco2ts(o)  \
    419 	check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))
    420 #define gco2u(o)  check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u))
    421 #define gco2lcl(o)  check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l))
    422 #define gco2ccl(o)  check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c))
    423 #define gco2cl(o)  \
    424 	check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))
    425 #define gco2t(o)  check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h))
    426 #define gco2p(o)  check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p))
    427 #define gco2th(o)  check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th))
    428 #define gco2upv(o)	check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv))
    429 
    430 
    431 /*
    432 ** macro to convert a Lua object into a GCObject
    433 ** (The access to 'tt' tries to ensure that 'v' is actually a Lua object.)
    434 */
    435 #define obj2gco(v)	check_exp((v)->tt >= LUA_TSTRING, &(cast_u(v)->gc))
    436 
    437 
    438 /* actual number of total memory allocated */
    439 #define gettotalbytes(g)	((g)->GCtotalbytes - (g)->GCdebt)
    440 
    441 
    442 LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);
    443 LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
    444 LUAI_FUNC lu_mem luaE_threadsize (lua_State *L);
    445 LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
    446 LUAI_FUNC void luaE_shrinkCI (lua_State *L);
    447 LUAI_FUNC void luaE_checkcstack (lua_State *L);
    448 LUAI_FUNC void luaE_incCstack (lua_State *L);
    449 LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont);
    450 LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where);
    451 LUAI_FUNC TStatus luaE_resetthread (lua_State *L, TStatus status);
    452 
    453 
    454 #endif
    455