/*1** $Id: lstate.h $2** Global State3** See Copyright Notice in lua.h4*/56#ifndef lstate_h7#define lstate_h89#include "lua.h"101112/* Some header files included here need this definition */13typedef struct CallInfo CallInfo;141516#include "lobject.h"17#include "ltm.h"18#include "lzio.h"192021/*22** Some notes about garbage-collected objects: All objects in Lua must23** be kept somehow accessible until being freed, so all objects always24** belong to one (and only one) of these lists, using field 'next' of25** the 'CommonHeader' for the link:26**27** 'allgc': all objects not marked for finalization;28** 'finobj': all objects marked for finalization;29** 'tobefnz': all objects ready to be finalized;30** 'fixedgc': all objects that are not to be collected (currently31** only small strings, such as reserved words).32**33** For the generational collector, some of these lists have marks for34** generations. Each mark points to the first element in the list for35** that particular generation; that generation goes until the next mark.36**37** 'allgc' -> 'survival': new objects;38** 'survival' -> 'old': objects that survived one collection;39** 'old1' -> 'reallyold': objects that became old in last collection;40** 'reallyold' -> NULL: objects old for more than one cycle.41**42** 'finobj' -> 'finobjsur': new objects marked for finalization;43** 'finobjsur' -> 'finobjold1': survived """";44** 'finobjold1' -> 'finobjrold': just old """";45** 'finobjrold' -> NULL: really old """".46**47** All lists can contain elements older than their main ages, due48** to 'luaC_checkfinalizer' and 'udata2finalize', which move49** objects between the normal lists and the "marked for finalization"50** lists. Moreover, barriers can age young objects in young lists as51** OLD0, which then become OLD1. However, a list never contains52** elements younger than their main ages.53**54** The generational collector also uses a pointer 'firstold1', which55** points to the first OLD1 object in the list. It is used to optimize56** 'markold'. (Potentially OLD1 objects can be anywhere between 'allgc'57** and 'reallyold', but often the list has no OLD1 objects or they are58** after 'old1'.) Note the difference between it and 'old1':59** 'firstold1': no OLD1 objects before this point; there can be all60** ages after it.61** 'old1': no objects younger than OLD1 after this point.62*/6364/*65** Moreover, there is another set of lists that control gray objects.66** These lists are linked by fields 'gclist'. (All objects that67** can become gray have such a field. The field is not the same68** in all objects, but it always has this name.) Any gray object69** must belong to one of these lists, and all objects in these lists70** must be gray (with two exceptions explained below):71**72** 'gray': regular gray objects, still waiting to be visited.73** 'grayagain': objects that must be revisited at the atomic phase.74** That includes75** - black objects got in a write barrier;76** - all kinds of weak tables during propagation phase;77** - all threads.78** 'weak': tables with weak values to be cleared;79** 'ephemeron': ephemeron tables with white->white entries;80** 'allweak': tables with weak keys and/or weak values to be cleared.81**82** The exceptions to that "gray rule" are:83** - TOUCHED2 objects in generational mode stay in a gray list (because84** they must be visited again at the end of the cycle), but they are85** marked black because assignments to them must activate barriers (to86** move them back to TOUCHED1).87** - Open upvales are kept gray to avoid barriers, but they stay out88** of gray lists. (They don't even have a 'gclist' field.)89*/90919293/*94** About 'nCcalls': This count has two parts: the lower 16 bits counts95** the number of recursive invocations in the C stack; the higher96** 16 bits counts the number of non-yieldable calls in the stack.97** (They are together so that we can change and save both with one98** instruction.)99*/100101102/* true if this thread does not have non-yieldable calls in the stack */103#define yieldable(L) (((L)->nCcalls & 0xffff0000) == 0)104105/* real number of C calls */106#define getCcalls(L) ((L)->nCcalls & 0xffff)107108109/* Increment the number of non-yieldable calls */110#define incnny(L) ((L)->nCcalls += 0x10000)111112/* Decrement the number of non-yieldable calls */113#define decnny(L) ((L)->nCcalls -= 0x10000)114115/* Non-yieldable call increment */116#define nyci (0x10000 | 1)117118119120121struct lua_longjmp; /* defined in ldo.c */122123124/*125** Atomic type (relative to signals) to better ensure that 'lua_sethook'126** is thread safe127*/128#if !defined(l_signalT)129#include <signal.h>130#define l_signalT sig_atomic_t131#endif132133134/*135** Extra stack space to handle TM calls and some other extras. This136** space is not included in 'stack_last'. It is used only to avoid stack137** checks, either because the element will be promptly popped or because138** there will be a stack check soon after the push. Function frames139** never use this extra space, so it does not need to be kept clean.140*/141#define EXTRA_STACK 5142143144#define BASIC_STACK_SIZE (2*LUA_MINSTACK)145146#define stacksize(th) cast_int((th)->stack_last.p - (th)->stack.p)147148149/* kinds of Garbage Collection */150#define KGC_INC 0 /* incremental gc */151#define KGC_GEN 1 /* generational gc */152153154typedef struct stringtable {155TString **hash;156int nuse; /* number of elements */157int size;158} stringtable;159160161/*162** Information about a call.163** About union 'u':164** - field 'l' is used only for Lua functions;165** - field 'c' is used only for C functions.166** About union 'u2':167** - field 'funcidx' is used only by C functions while doing a168** protected call;169** - field 'nyield' is used only while a function is "doing" an170** yield (from the yield until the next resume);171** - field 'nres' is used only while closing tbc variables when172** returning from a function;173** - field 'transferinfo' is used only during call/returnhooks,174** before the function starts or after it ends.175*/176struct CallInfo {177StkIdRel func; /* function index in the stack */178StkIdRel top; /* top for this function */179struct CallInfo *previous, *next; /* dynamic call link */180union {181struct { /* only for Lua functions */182const Instruction *savedpc;183volatile l_signalT trap; /* function is tracing lines/counts */184int nextraargs; /* # of extra arguments in vararg functions */185} l;186struct { /* only for C functions */187lua_KFunction k; /* continuation in case of yields */188ptrdiff_t old_errfunc;189lua_KContext ctx; /* context info. in case of yields */190} c;191} u;192union {193int funcidx; /* called-function index */194int nyield; /* number of values yielded */195int nres; /* number of values returned */196struct { /* info about transferred values (for call/return hooks) */197unsigned short ftransfer; /* offset of first value transferred */198unsigned short ntransfer; /* number of values transferred */199} transferinfo;200} u2;201short nresults; /* expected number of results from this function */202unsigned short callstatus;203};204205206/*207** Bits in CallInfo status208*/209#define CIST_OAH (1<<0) /* original value of 'allowhook' */210#define CIST_C (1<<1) /* call is running a C function */211#define CIST_FRESH (1<<2) /* call is on a fresh "luaV_execute" frame */212#define CIST_HOOKED (1<<3) /* call is running a debug hook */213#define CIST_YPCALL (1<<4) /* doing a yieldable protected call */214#define CIST_TAIL (1<<5) /* call was tail called */215#define CIST_HOOKYIELD (1<<6) /* last hook called yielded */216#define CIST_FIN (1<<7) /* function "called" a finalizer */217#define CIST_TRAN (1<<8) /* 'ci' has transfer information */218#define CIST_CLSRET (1<<9) /* function is closing tbc variables */219/* Bits 10-12 are used for CIST_RECST (see below) */220#define CIST_RECST 10221#if defined(LUA_COMPAT_LT_LE)222#define CIST_LEQ (1<<13) /* using __lt for __le */223#endif224225226/*227** Field CIST_RECST stores the "recover status", used to keep the error228** status while closing to-be-closed variables in coroutines, so that229** Lua can correctly resume after an yield from a __close method called230** because of an error. (Three bits are enough for error status.)231*/232#define getcistrecst(ci) (((ci)->callstatus >> CIST_RECST) & 7)233#define setcistrecst(ci,st) \234check_exp(((st) & 7) == (st), /* status must fit in three bits */ \235((ci)->callstatus = ((ci)->callstatus & ~(7 << CIST_RECST)) \236| ((st) << CIST_RECST)))237238239/* active function is a Lua function */240#define isLua(ci) (!((ci)->callstatus & CIST_C))241242/* call is running Lua code (not a hook) */243#define isLuacode(ci) (!((ci)->callstatus & (CIST_C | CIST_HOOKED)))244245/* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */246#define setoah(st,v) ((st) = ((st) & ~CIST_OAH) | (v))247#define getoah(st) ((st) & CIST_OAH)248249250/*251** 'global state', shared by all threads of this state252*/253typedef struct global_State {254lua_Alloc frealloc; /* function to reallocate memory */255void *ud; /* auxiliary data to 'frealloc' */256l_mem totalbytes; /* number of bytes currently allocated - GCdebt */257l_mem GCdebt; /* bytes allocated not yet compensated by the collector */258lu_mem GCestimate; /* an estimate of the non-garbage memory in use */259lu_mem lastatomic; /* see function 'genstep' in file 'lgc.c' */260stringtable strt; /* hash table for strings */261TValue l_registry;262TValue nilvalue; /* a nil value */263unsigned int seed; /* randomized seed for hashes */264lu_byte currentwhite;265lu_byte gcstate; /* state of garbage collector */266lu_byte gckind; /* kind of GC running */267lu_byte gcstopem; /* stops emergency collections */268lu_byte genminormul; /* control for minor generational collections */269lu_byte genmajormul; /* control for major generational collections */270lu_byte gcstp; /* control whether GC is running */271lu_byte gcemergency; /* true if this is an emergency collection */272lu_byte gcpause; /* size of pause between successive GCs */273lu_byte gcstepmul; /* GC "speed" */274lu_byte gcstepsize; /* (log2 of) GC granularity */275GCObject *allgc; /* list of all collectable objects */276GCObject **sweepgc; /* current position of sweep in list */277GCObject *finobj; /* list of collectable objects with finalizers */278GCObject *gray; /* list of gray objects */279GCObject *grayagain; /* list of objects to be traversed atomically */280GCObject *weak; /* list of tables with weak values */281GCObject *ephemeron; /* list of ephemeron tables (weak keys) */282GCObject *allweak; /* list of all-weak tables */283GCObject *tobefnz; /* list of userdata to be GC */284GCObject *fixedgc; /* list of objects not to be collected */285/* fields for generational collector */286GCObject *survival; /* start of objects that survived one GC cycle */287GCObject *old1; /* start of old1 objects */288GCObject *reallyold; /* objects more than one cycle old ("really old") */289GCObject *firstold1; /* first OLD1 object in the list (if any) */290GCObject *finobjsur; /* list of survival objects with finalizers */291GCObject *finobjold1; /* list of old1 objects with finalizers */292GCObject *finobjrold; /* list of really old objects with finalizers */293struct lua_State *twups; /* list of threads with open upvalues */294lua_CFunction panic; /* to be called in unprotected errors */295struct lua_State *mainthread;296TString *memerrmsg; /* message for memory-allocation errors */297TString *tmname[TM_N]; /* array with tag-method names */298struct Table *mt[LUA_NUMTYPES]; /* metatables for basic types */299TString *strcache[STRCACHE_N][STRCACHE_M]; /* cache for strings in API */300lua_WarnFunction warnf; /* warning function */301void *ud_warn; /* auxiliary data to 'warnf' */302} global_State;303304305/*306** 'per thread' state307*/308struct lua_State {309CommonHeader;310lu_byte status;311lu_byte allowhook;312unsigned short nci; /* number of items in 'ci' list */313StkIdRel top; /* first free slot in the stack */314global_State *l_G;315CallInfo *ci; /* call info for current function */316StkIdRel stack_last; /* end of stack (last element + 1) */317StkIdRel stack; /* stack base */318UpVal *openupval; /* list of open upvalues in this stack */319StkIdRel tbclist; /* list of to-be-closed variables */320GCObject *gclist;321struct lua_State *twups; /* list of threads with open upvalues */322struct lua_longjmp *errorJmp; /* current error recover point */323CallInfo base_ci; /* CallInfo for first level (C calling Lua) */324volatile lua_Hook hook;325ptrdiff_t errfunc; /* current error handling function (stack index) */326l_uint32 nCcalls; /* number of nested (non-yieldable | C) calls */327int oldpc; /* last pc traced */328int basehookcount;329int hookcount;330volatile l_signalT hookmask;331};332333334#define G(L) (L->l_G)335336/*337** 'g->nilvalue' being a nil value flags that the state was completely338** build.339*/340#define completestate(g) ttisnil(&g->nilvalue)341342343/*344** Union of all collectable objects (only for conversions)345** ISO C99, 6.5.2.3 p.5:346** "if a union contains several structures that share a common initial347** sequence [...], and if the union object currently contains one348** of these structures, it is permitted to inspect the common initial349** part of any of them anywhere that a declaration of the complete type350** of the union is visible."351*/352union GCUnion {353GCObject gc; /* common header */354struct TString ts;355struct Udata u;356union Closure cl;357struct Table h;358struct Proto p;359struct lua_State th; /* thread */360struct UpVal upv;361};362363364/*365** ISO C99, 6.7.2.1 p.14:366** "A pointer to a union object, suitably converted, points to each of367** its members [...], and vice versa."368*/369#define cast_u(o) cast(union GCUnion *, (o))370371/* macros to convert a GCObject into a specific value */372#define gco2ts(o) \373check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))374#define gco2u(o) check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u))375#define gco2lcl(o) check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l))376#define gco2ccl(o) check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c))377#define gco2cl(o) \378check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))379#define gco2t(o) check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h))380#define gco2p(o) check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p))381#define gco2th(o) check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th))382#define gco2upv(o) check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv))383384385/*386** macro to convert a Lua object into a GCObject387** (The access to 'tt' tries to ensure that 'v' is actually a Lua object.)388*/389#define obj2gco(v) check_exp((v)->tt >= LUA_TSTRING, &(cast_u(v)->gc))390391392/* actual number of total bytes allocated */393#define gettotalbytes(g) cast(lu_mem, (g)->totalbytes + (g)->GCdebt)394395LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);396LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);397LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);398LUAI_FUNC void luaE_shrinkCI (lua_State *L);399LUAI_FUNC void luaE_checkcstack (lua_State *L);400LUAI_FUNC void luaE_incCstack (lua_State *L);401LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont);402LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where);403LUAI_FUNC int luaE_resetthread (lua_State *L, int status);404405406#endif407408409410