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': each thread in Lua (a lua_State) keeps a count of
91 ** how many "C calls" it still can do in the C stack, to avoid C-stack
92 ** overflow.  This count is very rough approximation; it considers only
93 ** recursive functions inside the interpreter, as non-recursive calls
94 ** can be considered using a fixed (although unknown) amount of stack
95 ** space.
96 **
97 ** The count has two parts: the lower part is the count itself; the
98 ** higher part counts the number of non-yieldable calls in the stack.
99 ** (They are together so that we can change both with one instruction.)
100 **
101 ** Because calls to external C functions can use an unknown amount
102 ** of space (e.g., functions using an auxiliary buffer), calls
103 ** to these functions add more than one to the count (see CSTACKCF).
104 **
105 ** The proper count excludes the number of CallInfo structures allocated
106 ** by Lua, as a kind of "potential" calls. So, when Lua calls a function
107 ** (and "consumes" one CallInfo), it needs neither to decrement nor to
108 ** check 'nCcalls', as its use of C stack is already accounted for.
109 */
110 
111 /* number of "C stack slots" used by an external C function */
112 #define CSTACKCF	10
113 
114 
115 /*
116 ** The C-stack size is sliced in the following zones:
117 ** - larger than CSTACKERR: normal stack;
118 ** - [CSTACKMARK, CSTACKERR]: buffer zone to signal a stack overflow;
119 ** - [CSTACKCF, CSTACKERRMARK]: error-handling zone;
120 ** - below CSTACKERRMARK: buffer zone to signal overflow during overflow;
121 ** (Because the counter can be decremented CSTACKCF at once, we need
122 ** the so called "buffer zones", with at least that size, to properly
123 ** detect a change from one zone to the next.)
124 */
125 #define CSTACKERR	(8 * CSTACKCF)
126 #define CSTACKMARK	(CSTACKERR - (CSTACKCF + 2))
127 #define CSTACKERRMARK	(CSTACKCF + 2)
128 
129 
130 /* initial limit for the C-stack of threads */
131 #define CSTACKTHREAD	(2 * CSTACKERR)
132 
133 
134 /* true if this thread does not have non-yieldable calls in the stack */
135 #define yieldable(L)		(((L)->nCcalls & 0xffff0000) == 0)
136 
137 /* real number of C calls */
138 #define getCcalls(L)	((L)->nCcalls & 0xffff)
139 
140 
141 /* Increment the number of non-yieldable calls */
142 #define incnny(L)	((L)->nCcalls += 0x10000)
143 
144 /* Decrement the number of non-yieldable calls */
145 #define decnny(L)	((L)->nCcalls -= 0x10000)
146 
147 /* Increment the number of non-yieldable calls and decrement nCcalls */
148 #define incXCcalls(L)	((L)->nCcalls += 0x10000 - CSTACKCF)
149 
150 /* Decrement the number of non-yieldable calls and increment nCcalls */
151 #define decXCcalls(L)	((L)->nCcalls -= 0x10000 - CSTACKCF)
152 
153 
154 
155 
156 
157 
158 struct lua_longjmp;  /* defined in ldo.c */
159 
160 
161 /*
162 ** Atomic type (relative to signals) to better ensure that 'lua_sethook'
163 ** is thread safe
164 */
165 #if !defined(l_signalT)
166 #include <signal.h>
167 #define l_signalT	sig_atomic_t
168 #endif
169 
170 
171 /* extra stack space to handle TM calls and some other extras */
172 #define EXTRA_STACK   5
173 
174 
175 #define BASIC_STACK_SIZE        (2*LUA_MINSTACK)
176 
177 
178 /* kinds of Garbage Collection */
179 #define KGC_INC		0	/* incremental gc */
180 #define KGC_GEN		1	/* generational gc */
181 
182 
183 typedef struct stringtable {
184   TString **hash;
185   int nuse;  /* number of elements */
186   int size;
187 } stringtable;
188 
189 
190 /*
191 ** Information about a call.
192 */
193 typedef struct CallInfo {
194   StkId func;  /* function index in the stack */
195   StkId	top;  /* top for this function */
196   struct CallInfo *previous, *next;  /* dynamic call link */
197   union {
198     struct {  /* only for Lua functions */
199       const Instruction *savedpc;
200       volatile l_signalT trap;
201       int nextraargs;  /* # of extra arguments in vararg functions */
202     } l;
203     struct {  /* only for C functions */
204       lua_KFunction k;  /* continuation in case of yields */
205       ptrdiff_t old_errfunc;
206       lua_KContext ctx;  /* context info. in case of yields */
207     } c;
208   } u;
209   union {
210     int funcidx;  /* called-function index */
211     int nyield;  /* number of values yielded */
212     struct {  /* info about transferred values (for call/return hooks) */
213       unsigned short ftransfer;  /* offset of first value transferred */
214       unsigned short ntransfer;  /* number of values transferred */
215     } transferinfo;
216   } u2;
217   short nresults;  /* expected number of results from this function */
218   unsigned short callstatus;
219 } CallInfo;
220 
221 
222 /*
223 ** Bits in CallInfo status
224 */
225 #define CIST_OAH	(1<<0)	/* original value of 'allowhook' */
226 #define CIST_C		(1<<1)	/* call is running a C function */
227 #define CIST_HOOKED	(1<<2)	/* call is running a debug hook */
228 #define CIST_YPCALL	(1<<3)	/* call is a yieldable protected call */
229 #define CIST_TAIL	(1<<4)	/* call was tail called */
230 #define CIST_HOOKYIELD	(1<<5)	/* last hook called yielded */
231 #define CIST_FIN	(1<<6)  /* call is running a finalizer */
232 #define CIST_TRAN	(1<<7)	/* 'ci' has transfer information */
233 #if defined(LUA_COMPAT_LT_LE)
234 #define CIST_LEQ	(1<<8)  /* using __lt for __le */
235 #endif
236 
237 /* active function is a Lua function */
238 #define isLua(ci)	(!((ci)->callstatus & CIST_C))
239 
240 /* call is running Lua code (not a hook) */
241 #define isLuacode(ci)	(!((ci)->callstatus & (CIST_C | CIST_HOOKED)))
242 
243 /* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */
244 #define setoah(st,v)	((st) = ((st) & ~CIST_OAH) | (v))
245 #define getoah(st)	((st) & CIST_OAH)
246 
247 
248 /*
249 ** 'global state', shared by all threads of this state
250 */
251 typedef struct global_State {
252   lua_Alloc frealloc;  /* function to reallocate memory */
253   void *ud;         /* auxiliary data to 'frealloc' */
254   l_mem totalbytes;  /* number of bytes currently allocated - GCdebt */
255   l_mem GCdebt;  /* bytes allocated not yet compensated by the collector */
256   lu_mem GCestimate;  /* an estimate of the non-garbage memory in use */
257   lu_mem lastatomic;  /* see function 'genstep' in file 'lgc.c' */
258   stringtable strt;  /* hash table for strings */
259   TValue l_registry;
260   TValue nilvalue;  /* a nil value */
261   unsigned int seed;  /* randomized seed for hashes */
262   lu_byte currentwhite;
263   lu_byte gcstate;  /* state of garbage collector */
264   lu_byte gckind;  /* kind of GC running */
265   lu_byte genminormul;  /* control for minor generational collections */
266   lu_byte genmajormul;  /* control for major generational collections */
267   lu_byte gcrunning;  /* true if GC is running */
268   lu_byte gcemergency;  /* true if this is an emergency collection */
269   lu_byte gcpause;  /* size of pause between successive GCs */
270   lu_byte gcstepmul;  /* GC "speed" */
271   lu_byte gcstepsize;  /* (log2 of) GC granularity */
272   GCObject *allgc;  /* list of all collectable objects */
273   GCObject **sweepgc;  /* current position of sweep in list */
274   GCObject *finobj;  /* list of collectable objects with finalizers */
275   GCObject *gray;  /* list of gray objects */
276   GCObject *grayagain;  /* list of objects to be traversed atomically */
277   GCObject *weak;  /* list of tables with weak values */
278   GCObject *ephemeron;  /* list of ephemeron tables (weak keys) */
279   GCObject *allweak;  /* list of all-weak tables */
280   GCObject *tobefnz;  /* list of userdata to be GC */
281   GCObject *fixedgc;  /* list of objects not to be collected */
282   /* fields for generational collector */
283   GCObject *survival;  /* start of objects that survived one GC cycle */
284   GCObject *old1;  /* start of old1 objects */
285   GCObject *reallyold;  /* objects more than one cycle old ("really old") */
286   GCObject *firstold1;  /* first OLD1 object in the list (if any) */
287   GCObject *finobjsur;  /* list of survival objects with finalizers */
288   GCObject *finobjold1;  /* list of old1 objects with finalizers */
289   GCObject *finobjrold;  /* list of really old objects with finalizers */
290   struct lua_State *twups;  /* list of threads with open upvalues */
291   lua_CFunction panic;  /* to be called in unprotected errors */
292   struct lua_State *mainthread;
293   TString *memerrmsg;  /* message for memory-allocation errors */
294   TString *tmname[TM_N];  /* array with tag-method names */
295   struct Table *mt[LUA_NUMTAGS];  /* metatables for basic types */
296   TString *strcache[STRCACHE_N][STRCACHE_M];  /* cache for strings in API */
297   lua_WarnFunction warnf;  /* warning function */
298   void *ud_warn;         /* auxiliary data to 'warnf' */
299   unsigned int Cstacklimit;  /* current limit for the C stack */
300 } global_State;
301 
302 
303 /*
304 ** 'per thread' state
305 */
306 struct lua_State {
307   CommonHeader;
308   lu_byte status;
309   lu_byte allowhook;
310   unsigned short nci;  /* number of items in 'ci' list */
311   StkId top;  /* first free slot in the stack */
312   global_State *l_G;
313   CallInfo *ci;  /* call info for current function */
314   StkId stack_last;  /* last free slot in the stack */
315   StkId stack;  /* stack base */
316   UpVal *openupval;  /* list of open upvalues in this stack */
317   GCObject *gclist;
318   struct lua_State *twups;  /* list of threads with open upvalues */
319   struct lua_longjmp *errorJmp;  /* current error recover point */
320   CallInfo base_ci;  /* CallInfo for first level (C calling Lua) */
321   volatile lua_Hook hook;
322   ptrdiff_t errfunc;  /* current error handling function (stack index) */
323   l_uint32 nCcalls;  /* number of allowed nested C calls - 'nci' */
324   int oldpc;  /* last pc traced */
325   int stacksize;
326   int basehookcount;
327   int hookcount;
328   volatile l_signalT hookmask;
329 };
330 
331 
332 #define G(L)	(L->l_G)
333 
334 
335 /*
336 ** Union of all collectable objects (only for conversions)
337 ** ISO C99, 6.5.2.3 p.5:
338 ** "if a union contains several structures that share a common initial
339 ** sequence [...], and if the union object currently contains one
340 ** of these structures, it is permitted to inspect the common initial
341 ** part of any of them anywhere that a declaration of the complete type
342 ** of the union is visible."
343 */
344 union GCUnion {
345   GCObject gc;  /* common header */
346   struct TString ts;
347   struct Udata u;
348   union Closure cl;
349   struct Table h;
350   struct Proto p;
351   struct lua_State th;  /* thread */
352   struct UpVal upv;
353 };
354 
355 
356 /*
357 ** ISO C99, 6.7.2.1 p.14:
358 ** "A pointer to a union object, suitably converted, points to each of
359 ** its members [...], and vice versa."
360 */
361 #define cast_u(o)	cast(union GCUnion *, (o))
362 
363 /* macros to convert a GCObject into a specific value */
364 #define gco2ts(o)  \
365 	check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))
366 #define gco2u(o)  check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u))
367 #define gco2lcl(o)  check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l))
368 #define gco2ccl(o)  check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c))
369 #define gco2cl(o)  \
370 	check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))
371 #define gco2t(o)  check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h))
372 #define gco2p(o)  check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p))
373 #define gco2th(o)  check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th))
374 #define gco2upv(o)	check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv))
375 
376 
377 /*
378 ** macro to convert a Lua object into a GCObject
379 ** (The access to 'tt' tries to ensure that 'v' is actually a Lua object.)
380 */
381 #define obj2gco(v)	check_exp((v)->tt >= LUA_TSTRING, &(cast_u(v)->gc))
382 
383 
384 /* actual number of total bytes allocated */
385 #define gettotalbytes(g)	cast(lu_mem, (g)->totalbytes + (g)->GCdebt)
386 
387 LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);
388 LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
389 LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
390 LUAI_FUNC void luaE_freeCI (lua_State *L);
391 LUAI_FUNC void luaE_shrinkCI (lua_State *L);
392 LUAI_FUNC void luaE_enterCcall (lua_State *L);
393 LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont);
394 LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where);
395 
396 
397 #define luaE_exitCcall(L)	((L)->nCcalls++)
398 
399 #endif
400 
401