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